我有这张桌子:
id idsec type
1 a color
2 a description
3 b description
4 b food
5 b animal
6 c color
7 d descritpion
我想选择所有没有按 idsec 分组的“颜色”类型的 idsec。
您可以使用not exists:
select t.*
from table t
where not exists (select 1 from table t1 where t1.idsec = t.idsec and t1.type = 'color');
您还可以进行聚合:
select idsec
from table t
group by idsec
having sum(case when type = 'color' then 1 else 0 end) = 0;
使用下面的代码: -
select idsec from table
where idsec not in (select idsec from table where type = 'color')
group by idsec
一种选择是使用minus集合运算符
with t(id,idse,type) as
(
select 1,'a','color' from dual union all
select 2,'a','description' from dual union all
select 3,'b','description' from dual union all
select 4,'b','food' from dual union all
select 5,'b','animal' from dual union all
select 6,'c','color' from dual union all
select 7,'d','descritpion' from dual
)
select idse from t group by idse
minus
select idse from t where type = 'color';
IDSE
----
b
d
或者
select distinct idse from t
minus
select idse from t where type = 'color';
IDSE
----
b
d
您需要表中的不同值idsec:
SELECT
DISTINCT idsec
FROM tablename t
WHERE
NOT EXISTS (
SELECT 1 FROM tablename WHERE tablename.idsec = t.idsec AND tablename.type = 'color'
);