给定一个具有值(1,1)(1,4),(4,1)(2,2)的表(c1,c2),什么查询将允许我只输出c2 = 1的结果并且表中只有一个条目?在这种情况下,它只是(4,1),因为有两个条目,其中c1 = 1。 欢呼声。
答案 0 :(得分:0)
select c1, c2
from my_table t1
where c2 = 1
and 1 = (select count(*) from my_table t2 where t2.c1 = t1.c1)
其他一些方式:
select t1.c1, t1.c2
from my_table t1
join my_table t2 using (c1)
where t1.c2 = 1
group by t1.c1, t1.c2
having count(*) = 1;
select c1, c2
from my_table t1
where c2 = 1
and not exists (
select *
from from my_table t2
where t2.c1 = t1.c1
and t2.c2 <> t1.c2
);
select t1.c1, t1.c2
from my_table t1
left join my_table t2
on t2.c1 = t1.c1
and t2.c2 <> t1.c2
where t1.c2 = 1
and t2.c1 is null;
最后两个查询要求您的表格中没有重复项。