【发布时间】:2014-06-25 19:57:06
【问题描述】:
当我左加入这两个表“posts”和“cmets”时:
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 |
| ... | ... | ... |
| ... | ... | ... |
+----------+---------+----------+
【问题讨论】:
-
只需删除
count和group by。如果还想显示cmets的个数,那就把count(*)改成(select count(1) from comments where post_id = posts.id) as comment_count -
太棒了,谢谢伙计。我想我忽略了“GROUP BY”的含义