SQL query to select posts belonging to multiple categories

前端 未结 2 566
轮回少年
轮回少年 2021-01-07 07:54

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_i         


        
2条回答
  •  有刺的猬
    2021-01-07 08:34

    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)

提交回复
热议问题