日期:2014-05-17  浏览次数:20676 次

请教一个条件语句的条件限定范围,我的指导老师说比较难写。
表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。
请问有高手能写出来吗?

------解决方案--------------------
SQL code

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
*/

------解决方案--------------------
不好意思发错了
SQL code

select a.字段A, a.字段B from tmptb a
where a.字段B not in (select 字段B from tmptb where 字段A <> 'FLAG') and a.字段A='FLAG'