简体   繁体   English

SQL选择和与AND的内部联接

[英]SQL select and inner join with AND

Assume I have two SQL tables. 假设我有两个SQL表。 One that represents a post with columns (post_id, post_content) and one that represents tags associated to a post with columns (post_id, tag_text). 一个代表带有列的帖子(post_id,post_content),另一个代表与带有列的帖子关联的标签(post_id,tag_text)。

What do I have to do if I want to retrieve the post which have TAG1 and TAG2 , since a request like 如果我想检索包含TAG1TAG2的帖子,该TAG2 ,因为这样的请求

SELECT post_id FROM posts JOIN tags ON posts.post_id=tags.post_id 
WHERE tag_text ='TAG1' AND tag_text='TAG2'

obviously does not do what I want? 显然不做我想要的吗?

EDIT: Note that the number of AND is dynamically generated in my examples. 编辑:请注意,在我的示例中,AND的数量是动态生成的。 That is, it is not sufficient to double the inner join. 即,仅使内部联接加倍是不够的。

Here is the query: 这是查询:

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')

You can generate dynamic query (Dynamic EXISTS for each tag) if number of tag texts is not fixed. 如果标签文本的数量不固定,则可以生成动态查询(每个标签动态存在)。

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;

This will however also return posts that have more than those two tags (eg tag1, tag2 and tag3). 但是,这还将返回具有两个以上标签(例如tag1,tag2和tag3)的帖子。 If you don't want that, you need to limit the result to those posts which have exactly two tags: 如果您不希望这样做,则需要将结果限制为只有两个标签的帖子:

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

Btw: if you only want the post_id you don't need the join at all: 顺便说一句:如果您想要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.

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