表TABLE大致如下
字段A 字段B
-----------------
1. FLAG tang
2. FLAG song
3. OTHER song 我现在要写一个查询语句,通过条件 “字段A = FLAG” 把 tang 给查询出来的同时不把 song 给查询出来,因为第3条记录中song还关联了 OTHER.我原本想的是 select 字段B FROM TABLE WHERE 字段A IN ( FLAG )
但是没有用,上面两个语句会把记录1和2都查出来,而我只希望查出记录1。
请问有高手能写出来吗?
字段A 字段B
-----------------
1. FLAG tang
2. FLAG song
3. OTHER song 我现在要写一个查询语句,通过条件 “字段A = FLAG” 把 tang 给查询出来的同时不把 song 给查询出来,因为第3条记录中song还关联了 OTHER.我原本想的是 select 字段B FROM TABLE WHERE 字段A IN ( FLAG )
但是没有用,上面两个语句会把记录1和2都查出来,而我只希望查出记录1。
请问有高手能写出来吗?
with t(a,b) as(
select 'FLAG','tang' from dual
union select 'FLAG','song' from dual
union select 'OTHER','song' from dual
)
select b from t where a='FLAG'
and not exists (select * from t t1 where t1.b=t.b and t1.a<>'FLAG');
/*
B
------
tang
*/
对不起,可能没说的太清楚。这个OTHER表示这个字段有别的取值的,不仅仅是为OTHERS,也可能为CAT,DOG之类的任何值。
select a.字段A, a.字段B from tmptb a, (select 字段A, 字段B from tmptb where 字段A <> 'FLAG') b,
where a.字段B not in (select 字段B from tmptb where 字段A <> 'FLAG') and a.字段A='FLAG'
where a.字段B not in (select 字段B from tmptb where 字段A <> 'FLAG') and a.字段A='FLAG'
1楼正解,只要有不是FLAG的取值,都能查出来