首页 > 解决方案 > 使用连接的帖子的 MySQL 全选未选择(添加)标签

问题描述

要选择(查询)所有选择(添加)标签,我将使用代码:

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

如何使用连接查询所有未添加到帖子中的标签

帖子

ID 标题
1 帖子 1
2 帖子 2

标签

ID 姓名
1 标签 1
2 标签 2

post_tag

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

标签: phpmysqlsql

解决方案


如何查询所有未添加到帖子中的标签?

如果这是您的问题,方法是生成所有帖子/标签组合,然后删除存在的那些:

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

推荐阅读