多个连接和分组

时间:2015-02-25 06:26:11

标签: mysql sql join group-by

我有三张桌子,我试图创建一个视图。这三个表是,

消息

---------|---------|
newsID   |  title  | 
---------|---------|
  1      |  title1 |
  2      |  title2 |
  3      |  title3 |
---------|---------|

评论

-----------|----------|-----------|
commentID  |  newsID  |  comment  | 
-----------|----------|-----------|
  1        |     1    |           |   
  2        |     1    |           | 
  3        |     1    |           |
  4        |     1    |           |
  5        |     2    |           |    
-----------|----------|-----------|

-----------|----------|------|
voteID     |  newsID  | vote |
-----------|----------|------|
  1        |     1    |   5  |
  2        |     2    |   4  |    
  3        |     1    |   5  |
-----------|----------|------|

我的查询是

SELECT  news.newsID,  SUM(votes.vote) AS total,COUNT(comments.commentID) AS comment_count 
FROM news
LEFT JOIN votes ON news.newsID = votes.newsID 
LEFT JOIN comments ON news.newsID = comments.newsID
GROUP BY newsID

此查询的结果

-----------|----------|---------------|
newsID     |  total   | comment_count |
-----------|----------|---------------|
  1        |     40   |      8        |
  2        |     4    |      1        |    
  3        |    null  |      0        |
-----------|----------|---------------|

但它应该是这样的

-----------|----------|---------------|
newsID     |  total   | comment_count |
-----------|----------|---------------|
  1        |     10   |      4        |
  2        |     4    |      1        |    
  3        |    null  |      0        |
-----------|----------|---------------|

我将使用此查询创建视图,因此我无法使用子查询。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

实施此查询:

    SELECT news.newsID, (SELECT SUM(votes.vote) FROM votes WHERE votes.newsID = news.newsID) AS total, (SELECT COUNT(comments.commentID)FROM comments WHERE comments.newsID = news.newsID) AS comment_count
FROM news 
GROUP BY newsID