如何在子查询中使用Count?

时间:2019-02-08 21:49:05

标签: mysql sql

我在子查询中使用count遇到麻烦。我想编写一个查询,该查询将返回每个消费者的评论数,但计数是给我的总评论数。

SELECT con.Consumer_ID, con.Scheduled, con.Been_Called, (SELECT COUNT(*) 
FROM Comments WHERE com.ConsumerID = con.Consumer_ID) AS NumComments
FROM Consumers con
INNER JOIN Comments com
ON con.Consumer_ID = com.ConsumerID

我试图获取每个用户的评论数,但是NumComments却给了我Comments表中存在的评论总数。

3 个答案:

答案 0 :(得分:3)

似乎您使这一过程变得过于复杂。一个简单的聚合联接就可以解决问题,例如:

SELECT con.Consumer_ID, con.Scheduled, con.Been_Called, COUNT(*) as NumComments
FROM Consumers con
INNER JOIN Comments com ON com.Consumer_ID = con.ConsumerID
GROUP BY con.Consumer_ID, con.Scheduled, con.Been_Called

答案 1 :(得分:1)

您的子查询中的where子句不正确:

SELECT con.Consumer_ID, con.Scheduled, con.Been_Called, 
(
   SELECT COUNT(*) 
   FROM Comments c WHERE c.ConsumerID = con.Consumer_ID
) AS NumComments
FROM Consumers con

现在,它仅计算具有匹配的Consumer_id的评论

答案 2 :(得分:1)

SELECT con.Consumer_ID, con.Scheduled, con.Been_Called, COUNT(DISTINCT com.CommentID) AS NumComments
FROM Consumers con
INNER JOIN Comments com
ON con.Consumer_ID = com.ConsumerID
GROUP BY con.Consumer_ID, con.Scheduled, con.Been_Called