我正在制作一个博客,其中包含可以带有标签和评论的文章。我想尝试获得正确的 SQL 来获得一个查询。我有 4 张桌子:
article
+------------+-----------------+------------+
| article_id | title | photo |
+------------+-----------------+------------+
| 1 | This is a test | image1.jpg |
| 2 | Another Article | image2.jpg |
+------------+-----------------+------------+
article_tag
+------------+--------+
| article_id | tag_id |
+------------+--------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
+------------+--------+
tags
+--------+------+
| tag_id | name |
+--------+------+
| 1 | tag1 |
| 2 | tag2 |
+--------+------+
comment
+------+---------+------------+
| name | message | article_id |
+------+---------+------------+
| 1 | hello | 1 |
| 2 | a | 2 |
+------+---------+------------+
我试图得到这个:
+------------+----------------+------------+---------+----------+
| article_id | title | photo | tag_ids | comments |
+------------+----------------+------------+---------+----------+
| 1 | This is a test | image1.jpg | 1,2 | 1 |
+------------+----------------+------------+---------+----------+
这是我到目前为止所拥有的:
SELECT a.article_id, a.title, a.photo, a.date, a.description_long, a.author, GROUP_CONCAT(tag_id) as `tag_ids`, COUNT(c.comment_id) as comments
FROM article as a
JOIN article_tag as at
ON a.article_id = at.article_id
LEFT JOIN comment as c
ON a.article_id = c.article_id
WHERE a.article_id = 1
但是我收到的评论是 2 而不是 1?谢谢 PS 如果有人知道一种方法,我可以将 tag_ids 从 1,2 更改为 tag1,tag2 那就太棒了:-)