简体   繁体   中英

SQL query to select posts belonging to multiple categories

I am writing a web application similar to a blogging software. There are three tables as below

Posts Table: Post_id,Post_Text
Post_Tags Table: Post_id,Tag_id
Tags Table:Tag_id,Tag_name

I have a difficulty in conceptualizing a SQL query that will return posts that have 'all of the' tags in a given set.

This is relational division .

Use GROUP BY and COUNT or double NOT EXISTS .

An example of the first approach would be.

SELECT pt.Post_id, p.Post_Text
FROM Post_Tags pt
JOIN Posts p ON p.Post_id = pt.Post_id
WHERE pt.Tag_id IN (1,2,3)
GROUP BY pt.Post_id
HAVING COUNT(DISTINCT pt.Tag_id) = 3

Try this:

select * from posts where post_id in
(select post_id from post_tags pt join tags t on pt.tag_id = t.tag_id where tag_name = @yourtaghere)

or...

select
 p.*
from
 posts p join
 post_tags pt on p.post_id = pt.post_id join
 tags t on t.tag_id = pt.tag_id
where
 t.tag_name = @yourtaghere

If you have multiple tagnames you're trying to match replace tag_name = @youtagehere with tag_name in ('tag1','tag2','tag3',etc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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