我有四张桌子。
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
我遇到的问题是它没有返回正确的评论数。相反,它似乎返回标签的数量。请指教,谢谢你的时间:)
答案 0 :(得分:1)
尝试COUNT(distinct comments.id)