PostgreSQL-获取具有唯一列组合的记录

PostgreSQL-获取具有唯一列组合的记录,postgresql,unique,distinct,Postgresql,Unique,Distinct,我想选择在postgresql中具有唯一列组合的记录,但是它似乎不适用于distinct,因为distinct只删除重复项 范例 ID A B 01 1 2 02 1 2 03 1 3 04 2 4 05 1 4 06 2 4 07 2 5 08 1 3 在本例中,ID为05和07的行具有唯一的组合AB,如何获取这些记录 SELECT ... 不存在时: select t.* from tablename t where not exists ( s

我想选择在postgresql中具有唯一列组合的记录,但是它似乎不适用于distinct,因为distinct只删除重复项

范例

ID  A  B 
01  1  2
02  1  2
03  1  3
04  2  4
05  1  4
06  2  4
07  2  5
08  1  3
在本例中,ID为05和07的行具有唯一的组合AB,如何获取这些记录

SELECT ...

不存在时

select t.* from tablename t
where not exists (
  select 1 from tablename
  where id <> t.id and a = t.a and b = t.b
)
或使用聚合:

select max(id) id, a, b
from tablename
group by a, b
having count(id) = 1
或者使用排除匹配行的self
LEFT
联接:

select t.*
from tablename t left join tablename tt
on tt.id <> t.id and tt.a = t.a and tt.b = t.b
where tt.id is null
select t.*
from tablename t left join tablename tt
on tt.id <> t.id and tt.a = t.a and tt.b = t.b
where tt.id is null
| id  | a   | b   |
| --- | --- | --- |
| 05  | 1   | 4   |
| 07  | 2   | 5   |