我正在創建一篇文章,該文章可以包含標籤和評論。我想嘗試並獲得正確的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