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 に答える