我在同一个表中运行了两个查询:
SELECT id, COUNT(up)
FROM comentarios
WHERE up = 1
GROUP BY id
和
SELECT id, COUNT(down)
FROM comentarios
WHERE down = 2
GROUP BY id
我尝试了类似的东西但是没有用
SELECT t1.id, COUNT(t1.up), t2.id, COUNT(t2.down)
FROM (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
也许需要一个完整的外部加入?
在MySQL中执行此操作的最佳方法是什么?
答案 0 :(得分:1)
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
答案 1 :(得分:1)
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