[英]SQL select and inner join with AND
假设我有两个SQL表。 一个代表带有列的帖子(post_id,post_content),另一个代表与带有列的帖子关联的标签(post_id,tag_text)。
如果我想检索包含TAG1
和TAG2
的帖子,该TAG2
,因为这样的请求
SELECT post_id FROM posts JOIN tags ON posts.post_id=tags.post_id
WHERE tag_text ='TAG1' AND tag_text='TAG2'
显然不做我想要的吗?
编辑:请注意,在我的示例中,AND的数量是动态生成的。 即,仅使内部联接加倍是不够的。
这是查询:
SELECT * FROM posts p
WHERE
EXISTS ( SELECT 1 FROM tags t1 WHERE t1.post_id = p.post_id AND t1.tag_text='TAG1')
AND
EXISTS ( SELECT 1 FROM tags t2 WHERE t2.post_id = p.post_id AND t2.tag_text='TAG2')
如果标签文本的数量不固定,则可以生成动态查询(每个标签动态存在)。
select p.post_id
from posts p
join tags t ON p.post_id=t.post_id
where t.tag_text in ( 'TAG1', 'TAG2')
group by p.post_id
having count(distinct t.tag_text) = 2;
但是,这还将返回具有两个以上标签(例如tag1,tag2和tag3)的帖子。 如果您不希望这样做,则需要将结果限制为只有两个标签的帖子:
select p.post_id
from posts p
join tags t ON p.post_id=t.post_id
where t.tag_text in ( 'TAG1', 'TAG2')
group by p.post_id
having count(distinct t.tag_text) = 2
and count(distinct t.tag_text) = (select count(*)
from tags t2
where t2.post_id = t.post_id);
顺便说一句:如果您只想要post_id
,则根本不需要加入:
select post_id
from tags
where tag_text in ( 'TAG1', 'TAG2')
group by post_id
having count(distinct tag_text) = 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.