Join two queries with COUNT from the same table in MySQL
I have two queries that I run in the same table:
SELECT id, COUNT(up)
FROM comentarios
WHERE up = 1
GROUP BY id
And
SELECT id, COUNT(down)
FROM comentarios
WHERE down = 2
GROUP BY id
I tried something like this but doesn't work
SELECT t1.id, COUNT(t1.up), t2.id, COUNT(t2.down)
FROM 开发者_JS百科(SELECT id, up FROM comentarios WHERE up = 1 GROUP BY id) t1
JOIN (SELECT id, down FROM comentarios WHERE down = 2 GROUP BY id) t2
ON t1.id = t2.id
Maybe a need a FULL OUTER JOIN?
What's the best way to do this in MySQL?
SELECT id,
SUM(CASE WHEN up = 1 THEN 1 ELSE 0 END) AS UpCount,
SUM(CASE WHEN down = 2 THEN 1 ELSE 0 END) AS DownCount
FROM comentarios
GROUP BY id
select id,
sum(case when up = 1 then 1 end) as UpCount,
sum(case when down = 2 then 1 end) as DownCount
from comentarios
group by id
精彩评论