How to select categories and count the number of products in each category?

Asked

Viewed 3,804 times

6

I am trying to select the categories of the database and count in the same query the number of products registered in that category. So far so good, the problem is that I can not return to the category when there is no registered product, for example:

SELECT t1.id,t1.nome,t1.imagem,COUNT(*) AS Quantidade_produtos 
FROM categorias_produtos AS t1 
INNER JOIN produtos AS t2 ON t2.ref=t1.id 
GROUP BY t1.id

I have the categories:

categoria1
categoria2
categoria3

Products:

produto1 -> categoria1
produto2 -> categoria1
produto3 -> categoria2

I would like the result of the query to be more or less like this:

ID |   Nome   | Quantidade_produtos
 1 |categoria1|         2
 2 |categoria2|         1
 3 |categoria3|         0

However the query does not return this:

ID |   Nome   | Quantidade_produtos
 1 |categoria1|         2
 2 |categoria2|         1

You are ignoring the categories that have no registered product:

 3 |categoria3|         0

Any hint to be able to list all categories with the amount of products?

1 answer

9


Instead of INNER JOIN with the product table do LEFT JOIN:

SELECT t1.id,t1.nome,t1.imagem,COUNT(t2.*) AS Quantidade_produtos
FROM categorias_produtos AS t1
LEFT JOIN produtos AS t2 ON t2.ref=t1.id GROUP BY t1.id

Because the LEFT JOIN will take everything as long as it contains the record in the table on the left, since in Ner it would have to have the id in the two tables in order to return a result for that row and when it does not have the record in the product table, it will ignore this line if it is used Inner Join, so the use of left Join is correct

  • Why left Join? could complement the answer by explaining the difference?

  • LEFT JOIN will take everything as long as it contains the record in the table on the left, already in Inner it would have to have the id in the two tables so it can return a result for that row and when it does not have the record in the product table, it will ignore this line if it is used Inner Join, so the use of left Join is correct.

  • Hmmm, I did this and returned me quantity 1 for all who had 0, the others were right

  • change COUNT(*) to COUNT(t2.ref), as it will only count the product table records and not the two tables. Any doubt is just to say.

  • perfect, thank you very much :D

  • Mark as resolved. Obg.

  • 1

    @Leonardopatricio just a hint, edit your question, adding the explanation of LEFT JOIN in it. It is easier to read as an answer than as a comment by someone who is not used to the OS model (in case unsuspecting visitors)

Show 2 more comments

Browser other questions tagged

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