我有一个问题。在我的数据库中,我有 3 个表:
文章:
id title content date
标签:
id name
Tags_in_news:
id news_id tag_id
其中 news_id 是新闻表的外键,tag_id 是标签表的外键...如何选择文章及其附加的所有标签? 我创建了一个查询,但它为每个标签选择了一条新闻:
SELECT * FROM articles join tags_in_news
ON articles.id = tags_in_news.news_id
join tags on tags.id = tags_in_news.tag_id
ORDER BY date DESC
最佳答案
尝试 GROUP BY 文章和分组标签作为逗号分隔值
像这样:
SELECT
date, a.title, GROUP_CONCAT(DISTINCT t.name) as tags_attached
FROM articles a
JOIN tags_in_news tin ON a.id = tin.news_id
JOIN tags t ON t.id = tin.tag_id
GROUP BY a.id
ORDER BY date DESC
关于mysql - 从具有一对多关系的 3 个表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23535690/