è¡¨æ ¼ç»“æž„
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);
输出:
COULUMNS of articles after above query since used a.*
----------------
| id | content |
----------------
ç›®æ ‡ï¼š
在上é¢è¿è¡Œæ—¶ï¼Œæˆ‘获得了由“TAG1â€è¿‡æ»¤çš„æ‰€æœ‰æ–‡ç« åˆ—ã€‚ ä½†ç”±äºŽæ–‡ç« å¯èƒ½æœ‰å¤šä¸ªæ ‡ç¾ï¼Œæˆ‘想在返回的结果ä¸æ·»åŠ 一个列。 所以我的返回列将是
------------------------------
| id | content | using_tags |
------------------------------
| 1 | content | TAG1,TAG2 |
ç”案 0 :(得分: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