使用连接在mysql中按值计算

时间:2014-04-28 10:35:25

标签: 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

这是一个小问题:http://sqlfiddle.com/#!2/8e5241

现在我需要做的是查询所有主题并获取每个主题的每个主题的作者信息以及评论计数。这很容易解决这个问题:

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

这很好用,问题是我不仅需要整体评论计数。注释表中的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查询中执行此操作?

1 个答案:

答案 0 :(得分:3)

您需要使用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