Postgres:匹配连接中的多个值 table
Postgres: Match mutiple values in a join table
我有一个tablepost
POST TABLE
id | name
1 | post1
2 | post2
我有一个加入tablepost类别
POST CATEGORY (JOINT TABLE)
id | post_id | post_category_id
1 | 1 | 10
2 | 1 | 11
3 | 2 | 11
我如何 select post 同时拥有 post_category_id 10 和 11?
想要的结果:
POST TABLE
id | name
1 | post1
一种方法使用 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
当然,你可以join
在posts
,也可以用这个方法
我有一个tablepost
POST TABLE
id | name
1 | post1
2 | post2
我有一个加入tablepost类别
POST CATEGORY (JOINT TABLE)
id | post_id | post_category_id
1 | 1 | 10
2 | 1 | 11
3 | 2 | 11
我如何 select post 同时拥有 post_category_id 10 和 11?
想要的结果:
POST TABLE
id | name
1 | post1
一种方法使用 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
当然,你可以join
在posts
,也可以用这个方法