Retrieving all articles with GROUP_CONCAT field of their tags

I have a table articles, another tags, and a third - article_tags. I want to create a page that lists all 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 returned articles are japantagged, even if the article in question has multiple tags.

This is obviously related to the proposal WHERE, but I can't figure out how to do what I want here - ideally, I would get a list like japan,china,korea. Is this a place for a subquery? You can do with SQL gurus to advise.

Thanks Matt

+3
source share
2 answers

, , , . , . , , - . , , . :

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

, JOINs:

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;
+3

EXISTS:

   SELECT a.headline,
          GROUP_CONCAT(t.tag_name) AS all_tags
     FROM ARTICLES a
LEFT JOIN ARTICLES_TAGS at ON at.article_id = a.article_id
LEFT JOIN TAGS t ON t.tag_id = at.tag_id
    WHERE EXISTS(SELECT NULL
                   FROM ARTICLES x
                   JOIN ARTICLE_TAGS y ON y.article_id = x.article_id
                   JOIN TAGS z ON z.tag_id = y.tag_id
                              AND z.tag_name = 'japan'
                  WHERE x.article_id = a.article_id)
 GROUP BY a.article_id

LEFT JOINs , , "japan".

+2

Source: https://habr.com/ru/post/1761802/


All Articles