Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 具有特定标记的帖子的sql查询_Php_Mysql_Sql - Fatal编程技术网

Php 具有特定标记的帖子的sql查询

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

我有贴子,标签,贴子标签表

现在我想得到所有有(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_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
中选择*where
posts
ID
post\u tags
tags
ID
post\u-tags
中的
类似于使用
您想要使用的
你的问题不清楚:a,b,d是标签ID当然,tnx看起来是个好主意!我明天就试试!tnx
having count(*) = 3