我正在编写类似于博客软件的Web应用程序。 有三个表格如下
Posts Table: Post_id,Post_Text
Post_Tags Table: Post_id,Tag_id
Tags Table:Tag_id,Tag_name
我在构思SQL查询时遇到了困难,该查询将返回在给定集合中包含“所有”标记的帖子。
答案 0 :(得分:3)
使用GROUP BY
和COUNT
或加倍NOT EXISTS
。
第一种方法的一个例子是。
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
答案 1 :(得分:0)
试试这个:
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)
...或
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
如果你有多个你想要匹配的标记名替换tag_name = @youtagehere和tag_name('tag1','tag2','tag3'等)