我有一张桌子articles
, 其他tags
,第三个称为article_tags
。我想生成一个页面,其中列出特定标签的所有文章。
我的查询如下所示:
SELECT headline, GROUP_CONCAT(tags.tag_name) AS all_tags FROM articles
LEFT JOIN articles_tags ON articles.article_id = articles_tags.article_id
LEFT JOIN tags ON articles_tags.tag_id = tags.tag_id
WHERE tags.tag_name = 'japan'
GROUP BY articles.article_id
所有退回的文章只有japan
作为标签,即使相关文章有多个标签。
这显然与WHERE
子句,但我不知道如何在这里做我想做的事 - 理想情况下我最终会得到一个像这样的列表japan,china,korea
反而。这是子查询的地方吗?需要 SQL 专家的建议。
谢谢,
马特
您至少可以使用两种方法。一种方法是与表连接两次。正如您指出的另一个是使用子查询。为了简单性和易于阅读,我可能会在这里使用子查询。结果查询将如下所示:
SELECT
headline,
GROUP_CONCAT(tags.tag_name) AS all_tags
FROM articles
JOIN articles_tags ON articles.article_id = articles_tags.article_id
JOIN tags ON articles_tags.tag_id = tags.tag_id
WHERE articles.article_id IN (
SELECT articles.article_id
FROM articles
JOIN articles_tags ON articles.article_id = articles_tags.article_id
JOIN tags ON articles_tags.tag_id = tags.tag_id
WHERE tags.tag_name = 'japan'
)
GROUP BY articles.article_id
这是使用更多 JOIN 的方法:
SELECT
a.headline,
GROUP_CONCAT(t2.tag_name) AS all_tags
FROM articles a
JOIN articles_tags at1 ON a.article_id = at1.article_id
JOIN tags t1 ON at1.tag_id = t1.tag_id AND t1.tag_name = 'tag1'
JOIN articles_tags at2 ON a.article_id = at2.article_id
JOIN tags t2 ON at2.tag_id = t2.tag_id
GROUP BY a.article_id;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)