简体   繁体   中英

MySQL Select All not selected(added) tags for a post using joins

To select(query) all selected(added) tag I will use the code :

SELECT `tags`.`name`
FROM `post_tag` 
LEFT JOIN `tags` ON `post_tag`.`tag_id` = `tags`.`id` 
WHERE `post_tag`.`post_id` = '12'

How to query all the tags that are not added to a post using joins

posts

id title
1 post 1
2 post 2

tags

id name
1 tag 1
2 tag 2

post_tag

post_id tag_id
1 12
2 2
2 4
2 7
2 6
2 8

How to query all the tags that are not added to a post?

If this is your question, the approach is to generate all post/tag combinations and then remove the ones that exist:

select p.*, t.*
from posts p cross join
     tags t
     post_tags pt
     on pt.post_id = p.id and pt.tag_id = t.id
where pt.post_id is null;   -- there is no match

From my understand your question is: given a Post ID (eg 2), return all the tags that have not been associated with that particular Post Id. So in your example Tag 1 should be returned as it's not one of those associated with Post 2

If my interpretation is correct and you only want to use join you can use the following:

SELECT t.name
FROM tags AS t LEFT JOIN post_tag AS pt ON pt.tag_id = t.id
WHERE pt.tag_id IS NULL OR pt.post_id != 2
GROUP BY pt.tag_id;

What this query does is to take from the post_tag all tags that are either NULL (they are not joined with any existing post) or are joined with all posts except the one you're analysing (in your example, 2). The group by is to avoid duplicates.

Another more readable and efficient solution is to use a subquery

SELECT name FROM tags WHERE id NOT IN (
    SELECT tag_id FROM post_tag WHERE post_id = 2
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM