I have a table articles, another tags, and a third called article_tags. I want to produce a page which lists all of the articles for a specific tag.
My query looks like this:
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
All of the returned articles only have japan as a tag, even when the article in question has several tags.
This is obviously related to the WHERE clause, but I can’t figure out how to do what I want here – ideally I’d end up with a list like japan,china,korea instead. Is this the place for a subquery? Could do with a SQL guru to advise.
Thanks,
Matt
There are at least two approaches you could use. One approach is to join with the tables twice. The other as you point out is to use a subquery. For simiplicity and ease of reading, I’d probably go with the subquery here. The resulting query would look something like this:
And here’s the approach using more JOINs: