LEFT JOIN显示重复的匹配

时间:2014-06-25 19:57:07

标签: mysql sql join count

当我离开时加入这两个表的帖子和'评论':

SELECT *
FROM  `posts` 

+----+-----------+
| id | post_text |
+----+-----------+
|  1 | test0     |
|  2 | test1     |
|  3 | test2     |
|  4 | test3     |
|  5 | test4     |
|  6 | test5     |
|  7 | test6     |
|  8 | test7     |
|  9 | test8     |
| 10 | test9     |
| 11 | test10    |
+----+-----------+

SELECT *
FROM  `comments`

+----+------------------------------------------+---------+
| id |                 comment                  | post_id |
+----+------------------------------------------+---------+
|  1 | hello there                              |       4 |
|  2 | this is another comment on the same post |       4 |
|  3 | this is a comment on a different post    |       7 |
+----+------------------------------------------+---------+

我得到以下内容:

SELECT posts.id, post_id, COUNT( * ) 
FROM posts
LEFT JOIN posts ON posts.id = comments.post_id
GROUP BY posts.id

+----------+---------+----------+
| posts.id | post_id | COUNT(*) |
+----------+---------+----------+
| 4        | 4       | 2        |
| 7        | 7       | 1        |
| ...      | ...     | ...      |
| ...      | ...     | ...      |
+----------+---------+----------+

我想做的是,COUNT(*)大于1(意味着帖子上有多个评论),显示所有匹配的记录,而不是将它们分组成一行,所以它是像这样:

+----------+---------+----------+
| posts.id | post_id | COUNT(*) |
+----------+---------+----------+
| 4        | 4       | 1        |
| 4        | 4       | 1        |
| 7        | 7       | 1        |
| ...      | ...     | ...      |
| ...      | ...     | ...      |
+----------+---------+----------+

1 个答案:

答案 0 :(得分:1)

如果删除countgroup by,则可以选择所有记录。为了仍然显示每个帖子的评论数量,您可以使用相关的子查询。

另外,我认为您并不是真的想同时显示posts.idpost_id,因为它们是相同的值,因此以下查询应该更像您的意图:< / p>

select posts.id as post_id, comments.id as comment_id, (select count(1) from comments where post_id = posts.id) as comment_count
from posts
left join comments on posts.id = comments.post_id

这里是SQL Fiddle demo