我有一个包含以下三个值的表,没有通过schema施加任何其他约束
id_a id_b id_c
因此,可能有多行具有相同的id现在,我想编写一个查询,它将只给出id\u b唯一且与给定值匹配的行。比如:
select * where id_b = ? and (id_b is unique)
我知道这很简单,但我的大脑没有正常工作,所以任何帮助请。
bq9c1y661#
此查询:
select id_b from tablename group by id_b having count(*) = 1
返回所有 id_b 你想要的,所以和接线员一起使用 IN :
id_b
IN
select * from tablename where id_b in ( select id_b from tablename group by id_b having count(*) = 1 )
nimxete22#
这可能更简单,假设您有一个主键。然后你可以加上“和t2.id\u b=…”
SELECT t1.* FROM tablename as t1 LEFT JOIN tablename as t2 ON t1.id_b = t2.id_b AND t1.primarykey <> t2.primarykey WHERE t2.primarykey IS NULL
或以下语法:
SELECT t1.* FROM tablename as t1 WHERE NOT EXISTS (SELECT 'x' FROM tablename as t2 WHERE t1.id_b = t2.id_b AND t1.primarykey <> t2.primarykey)
zaqlnxep3#
如果需要行,请使用窗口函数:
select t.* from (select t.*, count(*) over (partition by b) as cnt_b from t ) t where t2.id_b = ? and cnt_b = 1;
如果你只是想 b 值,使用聚合:
b
select b from t group b having min(b) = max(b) and min(b) = ?;
3条答案
按热度按时间bq9c1y661#
此查询:
返回所有
id_b
你想要的,所以和接线员一起使用IN
:nimxete22#
这可能更简单,假设您有一个主键。然后你可以加上“和t2.id\u b=…”
或以下语法:
zaqlnxep3#
如果需要行,请使用窗口函数:
如果你只是想
b
值,使用聚合: