1

表结构:

articles (id, content)
article_tags (article_id, tag_id)
tag (id, name)

要按任何标签选择所有文章,请说我正在使用的“TAG1”

SELECT a.*
FROM  
    (SELECT at.article_id AS id
     FROM article_tags at
     JOIN tags t ON t.Id = at.tag_id
     WHERE t.name = 'TAG1') a1
JOIN articles a USING (id);

输出:

COLUMNS of articles after above query since used a.*
----------------
| id | content |  
----------------

客观的:

在上面运行时,我得到了由“TAG1”过滤的所有文章列。

但由于一篇文章可能有多个标签,我希望在返回的结果中增加一列。

所以我返回的列将是

| id | content |  using_tags |
+----+---------+-------------+ 
|  1 | content | TAG1,TAG2   |
4

1 回答 1

2

一个简单的方法...

SELECT a.*, GROUP_CONCAT(t2.name) AS using_tags
FROM (...inner query unchanged...) a1
INNER JOIN articles a USING (id)
LEFT JOIN article_tags at2 ON (a.id = at2.article_id)
LEFT JOIN tags t2 ON (t2.Id = at2.tag_id)
GROUP BY a.id
ORDER BY x
于 2013-05-12T14:10:10.577 回答