SQL - Category & Subcategory

Asked

Viewed 729 times

0

I have a category and subcategory structure. And I need to list all categories, and then their subcategories... But the listing went wrong. I’m using the codeigniter.

Structure of the Database:

inserir a descrição da imagem aqui

SQL structure:

SELECT c1.*,
       c2.id,
       c2.id_categoria,
       c2.categoria as nome_categoria
  FROM categoria AS c1
  LEFT JOIN categoria AS c2
    ON c2.id_categoria = c1.id

How do I list all the categories and subcategories correctly? Within the same SQL, because I will recover the data by foreach() to display all categories and their subcategories. Today the result is like this:

inserir a descrição da imagem aqui

This should be the result: inserir a descrição da imagem aqui

The health category should also appear in the example...

Show 2 more comments

1 answer

2


If I understand correctly, all main categories have id_category = 0, then:

SELECT * FROM (
    SELECT c1.id,
            c1.categoria as categoria_principal,
            null as sub_categoria
    FROM categoria AS c1

    WHERE c1.id_categoria = 0

    UNION

    SELECT c2.id,
            c1.categoria as categoria_principal,
            c2.categoria as sub_categoria
    FROM categoria AS c1
      INNER JOIN categoria AS c2 ON c2.id_categoria = c1.id

    WHERE c1.id_categoria = 0
) as tbaux
ORDER BY categoria_principal, sub_categoria

First search the main categories, then the main categories plus the subcategories

This is the result:

inserir a descrição da imagem aqui

Streamlined:

SELECT CASE WHEN c2.id IS NULL
                THEN c1.id
                ELSE c2.id
            END AS id,
        c1.categoria as categoria_principal,
        c2.categoria as sub_categoria
FROM categoria AS c1
  LEFT JOIN categoria AS c2 ON c2.id_categoria = c1.id

WHERE c1.id_categoria = 0
ORDER BY categoria_principal, sub_categoria
  • That’s almost it @Tiago Oliveira de Freita ....

  • I posted the result in your question, there remains a category...

  • I edited it, you can try it again, I’ll even post one more option, make it simple

  • Perfect, that’s right. Thank you so much!

  • Has a simpler version, should work too.

  • In the simplest version, one of the categories was missing...

  • Strange then ignores (y)

  • Good, it worked the first one and it’s OK! : ) Very Thanks!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.