PostgreSQL 全部
PostgreSQL IN all
我有以下 table 结构:
| id | object_id | status_id |
------------------------------
| 1 | 12 | 1 |
| 2 | 12 | 2 |
| 3 | 18 | 5 |
我需要 select 所有处于状态 1 和 2 的 object_id
。也就是说,像这样:select object_id from table_name where status_id in (1, 2)
,但我需要 status_id
不在列出的值之一中,而是在两个值中。也就是说,根据上面的 table,我应该 return 值 12(因为 object_id
在状态中等于 12)。如何做到这一点?
select object_id
from table_name
where status_id in (1, 2)
group by object_id
having count(distinct status_id) = 2
如果您只需要来自状态 1 或 2 的唯一对象 ID,那么您可以使用 distinct
关键字。:
select distinct object_id from table_name where status_id in (1, 2)
要获取那些 恰好 这两个状态值的对象 ID,您可以使用
select object_id
from the_table
group by object_id
having bool_and(status_id in (1,2))
and count(distinct status_id) = 2
我有以下 table 结构:
| id | object_id | status_id |
------------------------------
| 1 | 12 | 1 |
| 2 | 12 | 2 |
| 3 | 18 | 5 |
我需要 select 所有处于状态 1 和 2 的 object_id
。也就是说,像这样:select object_id from table_name where status_id in (1, 2)
,但我需要 status_id
不在列出的值之一中,而是在两个值中。也就是说,根据上面的 table,我应该 return 值 12(因为 object_id
在状态中等于 12)。如何做到这一点?
select object_id
from table_name
where status_id in (1, 2)
group by object_id
having count(distinct status_id) = 2
如果您只需要来自状态 1 或 2 的唯一对象 ID,那么您可以使用 distinct
关键字。:
select distinct object_id from table_name where status_id in (1, 2)
要获取那些 恰好 这两个状态值的对象 ID,您可以使用
select object_id
from the_table
group by object_id
having bool_and(status_id in (1,2))
and count(distinct status_id) = 2