使用连接在mysql中按值计数

使用连接在mysql中按值计数,mysql,join,Mysql,Join,我有三个表:用户、主题和帖子,它们的结构如下: --users ----id ----name ----email ----password ----profile_pic --topics ----id ----topic_title ----topic_category ----topic_content ----author_id --comments ----id ----topic_id ----author_id ----comment ----mood 这方面的一个sql版本

我有三个表:用户、主题和帖子,它们的结构如下:

--users
----id
----name
----email
----password
----profile_pic

--topics
----id
----topic_title
----topic_category
----topic_content
----author_id

--comments
----id
----topic_id
----author_id
----comment
----mood
这方面的一个sql版本位于:

现在我需要做的是查询所有主题,并获得每个主题的作者信息以及每个主题的评论数。这很容易完成此查询:

SELECT 
  topics.id, 
  topics.topic_title, 
  topics.topic_category, 
  topics.topic_content, 
  topics.author_id, 
  users.name, 
  users.profile_pic, 
  topics.created_at, 
  count(comments.id) AS comments 
FROM 
  topics 
JOIN 
  users 
ON 
  users.id = topics.author_id 
LEFT JOIN 
  comments 
ON 
  topics.id = comments.topic_id 
GROUP BY 
  topics.id 
ORDER BY 
  topics.created_at 
DESC
返回以下sql结果:

topic_title | created_at | id | topic_category | author_id | topic_content | name | profile_pic | comments
这很好,问题是我不需要总的评论数。comments表中的mood字段可以有3个可能的值(0、1、2),我需要用每个值计算注释的数量

我试着换衣服

count(comments.id)
在上面的查询中

count(comments.mood=0) AS happy, count(comments.mood=1) AS sad, count(comments.mood=2) AS angry
但这会为每个结果字段返回相同的值。在一个mySQL查询中有什么方法可以做到这一点吗?

您需要使用sum()来执行以下操作:

sum(comments.mood=0) as happy,
sum(comments.mood=1) as sad,
sum(comments.mood=2) as angry,
由@Pavel编辑:我将分享我用来获得正确结果的最后一个查询,该查询基于@Abhik Chakraborty和@Tomalak给出的答案

SELECT 
    topics.id, 
    topics.topic_title, 
    topics.topic_category, 
    topics.topic_content, 
    topics.author_id, 
    users.name AS author_name, 
    users.profile_pic, 
    topics.created_at, 
    IFNULL(SUM(comments.mood=0),0) AS comments_happy, 
    IFNULL(SUM(comments.mood=1),0) AS comments_sad, 
    IFNULL(SUM(comments.mood=2),0) AS comments_angry 
  FROM 
    topics 
  JOIN 
    users 
  ON 
    users.id = topics.author_id 
  LEFT JOIN 
    comments 
  ON topics.id = comments.topic_id 
  GROUP BY 
    topics.id 
  ORDER BY 
    topics.created_at 
  DESC

你可以试着把sum(comments.mood=0)设为高兴,以此类推……是的,这很有效。谢谢:)让我补充一下,作为回答@Pavel感谢您提供SQL小提琴,我的答案当然是完全错误的。很抱歉,我已经删除了。啊,太好了。IFNULL()解决了这个问题。我没想到。再次感谢您的帮助。:)