Postgres:匹配联接表中的多个值

时间:2020-03-25 12:49:18

标签: sql postgresql relational-division

我有一张桌子发帖

POST TABLE
id | name
 1 | post1
 2 | post2

我有一个联接表帖子类别

POST CATEGORY (JOINT TABLE)
id | post_id  | post_category_id
 1 |       1  |               10
 2 |       1  |               11
 3 |       2  |               11

我将如何选择同时具有post_category_id 10和11的帖子?

想要的结果:

POST TABLE
id | name
 1 | post1

1 个答案:

答案 0 :(得分:0)

一种方法使用exists

select p.*
from posts p
where exists (select 1
              from postcategory pc
              where pc.post_id = p.id and pc.category = 10
             ) and
      exists (select 1
              from postcategory pc
              where pc.post_id = p.id and pc.category = 11
             ) ;

如果您只想要ID,我建议进行汇总:

select pc.post_id
from postcategory pc
where pc.category in (10, 11)
group by pc.post_id
having count(*) = 2;  -- use count(distinct category) if the table can have duplicates

当然,您可以在joinposts并使用此方法。