postgres:在字段中查找具有一个特定值的记录

sc4hvdpw  于 2021-07-26  发布在  Java
关注(0)|答案(5)|浏览(322)

我有一张这样的table:

ID | Type
----------
 1 | Web
 1 | App
 2 | Web
 2 | Web
 3 | App

我想得到的ID只有'网络'的类型。我试过这个:

SELECT id FROM tbl
GROUP BY 1
HAVING COUNT(DISTINCT type) = 1

但是这给了我所有的id,不管类型是不是“web”。
我的预期结果是:

ID | Type
----------
 2 | Web
fslejnso

fslejnso1#

可以使用聚合:

select id
from t
group by id
having min(type) = max(type) and min(type) = 'Web';
ui7jx7zq

ui7jx7zq2#

我们可以在这里使用exists逻辑:

SELECT DISTINCT ID
FROM yourTable t1
WHERE
    t1.Type = 'Web' AND
    NOT EXISTS (SELECT 1 FROM yourTable t2
                WHERE t2.ID = t1.ID AND t2.Type <> 'Web');

演示

ds97pgxw

ds97pgxw3#

你可以试着用 not exists 演示

select distinct id, type from tablename t1
    where not exists
      ( select 1 from tablename t2 where t1.id=t2.id and t2.type<>'Web')
bksxznpy

bksxznpy4#

你可以用 SELECT id, count(*) as total FROM table_name WHERE type = 'Web' GROUP BY type HAVING total = 1)

q3qa4bjr

q3qa4bjr5#

试着像下面我刚刚编辑了你的答案添加了一个where子句

SELECT id FROM tbl t1
  where 
  t1.id in ( select id from tbl a where a.type='Web')
 GROUP BY id
 HAVING COUNT(DISTINCT type) = 1

相关问题