需要有关几乎可以工作的JOIN查询的帮助

时间:2010-02-16 01:45:51

标签: mysql

我有四张桌子。

posts
| id      | title     |
+---------+-----------+
| 1       | hello     |
| 2       | goodbye   |
+---------+-----------+

posts_tags
| tag_id  | post_id   |
+---------+-----------+
| 1       | 1         |
| 2       | 1         |
| 2       | 2         |
+---------+-----------+

comments
| id      | post_id    | comment   |
+---------+------------+-----------+
| 1       | 1          | hey       |
| 2       | 2          | what up   |
| 3       | 2          | blah      |
+---------+------------+-----------+

tags
| id      | name      |
+---------+-----------+
| 1       | news      |
| 2       | photos    |
+---------+-----------+

我希望能够选择帖子,但结果是

post.id    post.title    tags              comments
-----------------------------------------------------
1          hello         news,photos       1
2          goodbye       photos            2

这样的东西
SELECT *,
       GROUP_CONCAT(tags.name) AS tags,
       COUNT(comments.id) AS comments
FROM posts
    LEFT JOIN comments
        ON posts.id = comments.post_id
    LEFT JOIN posts_tags
        ON posts.id = posts_tags.post_id
    LEFT JOIN tags
        ON posts_tags.tag_id = tags.id
GROUP BY posts.id

我遇到的问题是它没有返回正确的评论数。相反,它似乎返回标签的数量。请指教,谢谢你的时间:)

1 个答案:

答案 0 :(得分:1)

尝试COUNT(distinct comments.id)