Count sql results in table having or not values

0

I have a subcategorias table and I have another anuncios , where it has the id of the subcategory. I need to fetch all subcategories and return by subcategory the number of ads it has, the problem is that I'm already generating the subcategories with another loop from another table. How could I do that?

SELECT * from 'subcategorias'
LEFT JOIN 'anuncios' ON 'subcategorias'.'id_subcategoria' = 'anuncios'.'id_anuncio'
WHERE 'anuncios'.'status' = 1;
So basically I have to list all the subcategories, and together, make a count of how many active ads each has and then I throw this loop on the page

    
asked by anonymous 06.12.2017 / 12:53

3 answers

0

What you can do is merge the results of categories that have no active ads to the category count that has active ads with this query :

select
subcategoria.nome,
coalesce(count(anuncios.id)) as quantidade
from subcategoria
left join anuncios on anuncios.id_subcategoria = subcategoria.id
where anuncios.status = 1
group by subcategoria.nome
union
select nome, '0' as quantidade from subcategoria
where subcategoria.id not in (select id_subcategoria from anuncios where status = 1)
order by nome

See this SQL Fiddle .

    
06.12.2017 / 13:35
0

Add a% w / o AS% qtd in your query and a COUNT(anuncios.*) subcategory.id_subcategory. But looking at it, the JOIN relationship seems to be wrong, but since the question is not the answer above, it looks like this:

    SELECT  
    s.*,
    count(*) as qtd
FROM subcategorias s
LEFT JOIN anuncios a
ON a.id_subcategoria = s.id_subcategoria
GROUP BY s.id_subcategoria
    
06.12.2017 / 13:10
0

I tried to edit here to be able to get by category requested but the quantity returned is always 1 record

I've edited here to get the requested category, but the quantity always reports as having a record

SELECT s.*, 
COUNT(*) AS qtd 
FROM subcategorias s 
JOIN categorias c 
ON c.id_categoria = s.id_categoria 
LEFT JOIN anuncios a 
ON a.id_subcategoria = s.id_subcategoria 
WHERE s.id_categoria = 6 
GROUP BY s.id_subcategoria
    
06.12.2017 / 13:36