Php 具有特定标记的帖子的sql查询
我有贴子,标签,贴子标签表 现在我想得到所有有(a,b,d)标签的帖子 我如何做到这一点,而不仅仅是获得所有贴子的一个/两个/所有标签Php 具有特定标记的帖子的sql查询,php,mysql,sql,Php,Mysql,Sql,我有贴子,标签,贴子标签表 现在我想得到所有有(a,b,d)标签的帖子 我如何做到这一点,而不仅仅是获得所有贴子的一个/两个/所有标签 tables: posts: id, title tags: id, title post_tags: post_id, tag_id 我的简单想法是这样一个问题: select * from post_tags pt join posts ps on pt.post_id=ps.id where pt.tag_id in (MY_DESIRED_TAG
tables:
posts:
id, title
tags:
id, title
post_tags:
post_id, tag_id
我的简单想法是这样一个问题:
select *
from post_tags pt
join posts ps on pt.post_id=ps.id
where pt.tag_id in (MY_DESIRED_TAGS)
这肯定不起作用,因为我得到的帖子只有一个标签,而不是所有标签
SELECT *
FROM posts ps
WHERE ps.id IN (
SELECT pt.post_id
FROM post_tags pt
WHERE pt.tag_id IN ([MY_DESIRED_TAGS])
GROUP BY pt.post_id
HAVING COUNT(1) = [THE_NUMBER_OF_DESIRED_TAGS]
)
;
子查询查找每个帖子的标签数量(在提供的标签中),并将帖子id值作为结果集。外部查询然后查找具有这些id值的帖子。如其他答案所示,它可以作为一个连接来完成,但我建议的方式可能更快,因为服务器不必处理与实际组操作无关的数据。您可以使用
分组方式和拥有:
select p.*
from posts p join
post_tags pt
on pt.post_id = p.id
where pt.tag_id in (MY_DESIRED_TAGS)
group by p.post_id
having count(*) = <# desired tags>;
“从posts
,tags
,post\u tags
中选择*whereposts
ID
,post\u tags
和tags
ID
post\u-tags
中的类似于使用或您想要使用的和你的问题不清楚:a,b,d是标签ID当然,tnx看起来是个好主意!我明天就试试!tnx
having count(*) = 3