简体   繁体   English

sql查询带有特定标签的帖子

[英]sql query for posts with specific tags

I have posts, tags, post_tags tables. 我有帖子,标签,post_tags表。

Now I want to get all posts that have (a, b, d) tags, 现在,我想获取所有具有(a,b,d)标签的帖子,

how do I achive that and not only getting all posts with one/two/all tags? 我该如何做到这一点,而不仅仅是获得带有一个/两个/所有标签的所有帖子?

tables:

posts:
id, title

tags:
id, title

post_tags:
post_id, tag_id

my simple idea was this query: 我的简单想法是此查询:

select *
from post_tags pt
join posts ps on pt.post_id=ps.id
where pt.tag_id in (MY_DESIRED_TAGS)

this surely doesn't work as i get posts with only one of the tags and not all of them. 这肯定行不通,因为我只收到其中一个标签而不是全部标签的帖子。

You can use group by and having : 您可以使用group byhaving

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>;

The key is counting the number of tags that match. 关键是计算匹配标签的数量。 If you have three tags, then the having clause would be: 如果您有三个标签,那么having子句将是:

having count(*) = 3
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]
)
;

The subquery finds the number of tags (out of the ones supplied) for every post and gives the post id values as a result set. 子查询查找每个帖子的标签数量(在提供的标签中),并提供帖子ID值作为结果集。 The outer query then finds the posts with those id values. 然后,外部查询将查找具有这些id值的帖子。 It can be done as a JOIN as other answers have indicated, but the way I have suggested might be faster since the server will not have to handle data irrelevant to the actual group operation. 可以像其他答案所示的那样,通过JOIN来完成,但是我建议的方法可能会更快,因为服务器不必处理与实际组操作无关的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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