我正在创建一篇文章,该文章可以包含标签和评论。我想尝试并获得正确的SQL来获得一个查询。 我有4个表:MySQL加入3个表并计算另一个
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将会非常惊人:-)
有没有所谓的'comment_id'在你的评语表列... – Terry 2013-02-23 22:39:01
数不同,它返回因为与商品标签中加入 – jazzytomato 2013-02-23 22:41:57
对不起忘了包括2号线在问题中。但我有一个 – supajason 2013-02-24 18:01:44