这是我的查询:
SELECT
p.PRO_Id, p.PRO_Name,
COUNT(DISTINCT c.COM_Id) as commentCount,
COUNT(DISTINCT d.DIS_Id) AS disCount,
d.DIS_ThreadDesc,
dev.DEV_Name,
loc.LOC_Name,
d.USE_Id,
d.DIS_Date
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
LEFT JOIN developer dev ON p.DEV_Id=dev.DEV_Id
LEFT JOIN locality loc ON p.LOC_Id=loc.LOC_Id
WHERE p.PRO_Status=1
and d.DIS_Status=1
and c.COM_Status=2
GROUP BY p.PRO_Id
ORDER BY 3 desc LIMIT 3
我想要得到的是commenCount(总评论)和disCount(总讨论)的总和。
我这样做了; -
sum(COUNT(DISTINCT c.COM_Id) + COUNT(DISTINCT d.DIS_Id)) AS totalResponse但是没机会。
答案 0 :(得分:4)
您可以添加COUNT
的结果:
SELECT
p.PRO_Id, p.PRO_Name,
COUNT(DISTINCT c.COM_Id) AS commentCount,
COUNT(DISTINCT d.DIS_Id) AS disCount,
COUNT(DISTINCT c.COM_Id) + COUNT(DISTINCT d.DIS_Id) AS totalResponse
d.DIS_ThreadDesc, dev.DEV_Name, loc.LOC_Name, d.USE_Id, d.DIS_Date
FROM projects p
...
或者使用子查询:
SELECT sub.*,
commentCount + disCount AS totalResponse
FROM (
SELECT
p.PRO_Id, p.PRO_Name,
COUNT(DISTINCT c.COM_Id) as commentCount,
COUNT(DISTINCT d.DIS_Id) AS disCount,
d.DIS_ThreadDesc,
dev.DEV_Name,
loc.LOC_Name,
d.USE_Id,
d.DIS_Date
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
LEFT JOIN developer dev ON p.DEV_Id=dev.DEV_Id
LEFT JOIN locality loc ON p.LOC_Id=loc.LOC_Id
WHERE p.PRO_Status=1
and d.DIS_Status=1
and c.COM_Status=2
GROUP BY p.PRO_Id
) AS sub
ORDER BY commentCount LIMIT 3
请注意,您的SELECT
列表与GROUP BY
不匹配。这适用于MySQL
,但不符合ANSI
标准。您应该在两个子句中使用相同的列表,或者对GROUP BY
中未指定的列使用聚合函数。更多信息here。