我有三个表projects
,discussions
和comments
。
我试过这样的话:
SELECT p.PRO_Name, COUNT( d.DIS_Id ) AS nofdisc, COUNT( c.COM_Id ) AS nofcom
FROM projects p
LEFT JOIN discussions d ON p.PRO_Id = d.PRO_Id
LEFT JOIN comments c ON d.DIS_Id = c.DIS_Id
GROUP BY p.PRO_Name LIMIT 0 , 30
但它从discussions
获取了所有行,而comments
的计数与discussions
的计数相同。
答案 0 :(得分:1)
count
计算给定参数的非null
值的数量。您拥有的联接会为每条评论创建一行,其中dis_id
和com_id
都不是null
,因此它们的计数将相同。由于这些是ID,因此您只需计算 distinct
出现次数即可获得您想要的响应:
(编辑:根据评论中的请求添加了order by
条款)
SELECT p.PRO_Name,
COUNT(DISTINCT d.DIS_Id) AS nofdisc,
COUNT(DISTINCT c.COM_Id) AS nofcom
FROM projects p
LEFT JOIN discussions d ON p.PRO_Id = d.PRO_Id
LEFT JOIN comments c ON d.DIS_Id = c.DIS_Id
GROUP BY p.PRO_Name
ORDER BY 2,3
LIMIT 0 , 30