我有帖子、标签、post_tags 表。
现在我想获取所有带有 (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)
这肯定行不通,因为我收到的帖子只有一个标签,而不是所有标签。
最佳答案
您可以使用group by
和having
:
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>;
关键是计算匹配的标签数量。如果您有三个标签,则 having
子句将是:
having count(*) = 3
关于php - sql查询具有特定标签的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30269091/