如何构造SQL子查询?

时间:2017-03-28 19:10:42

标签: sql oracle

select
e.EMPNO,
e.ENAME
from  
emp e
where 
e.DEPTNO in  (select case
                      when 'D'='D'  then q'[10,20]'
                       END DPT 
                  from dual )

修改:

真正的查询类似于

SELECT e.name, e.entid
  FROM ent e
 WHERE     e.etype = 'DPT'
       AND e.entid IN (
                        SELECT CASE
                                WHEN :P96_GP_TYPE = 'R' THEN q'['QUA','SAMP']'
                                WHEN :P96_GP_TYPE = 'REWR' THEN q'['WASH','FNISH']' END
                        FROM DUAL
                      )

1 个答案:

答案 0 :(得分:0)

您不需要子查询,但您可以更好地使用一些布尔逻辑:

SELECT e.name, e.entid
  FROM ent e
 WHERE     e.etype = 'DPT'
       AND (
                (:P96_GP_TYPE = 'R' AND e.entid IN ('QUA','SAMP') )
                 OR
                (:P96_GP_TYPE = 'REWR'  AND e.entid IN ('WASH','FNISH') )
           )

为了澄清您的方法失败的地方,请考虑这三个查询是完全等效的:

select *
from someTable
where someColumn in (  q'['X','Y']' )           

select *
from someTable
where someColumn in ( 
                     select q'['X','Y']'
                     from dual 
                    )

select *
from someTable
where someColumn in ( 
                     select '''X'',''Y'''
                     from dual 
                    )

如果要使用子查询来获取值列表,而不是看起来像值列表的文字,则需要以下内容:

select *
from someTable
where someColumn in (
                        select 'X'
                        from dual
                        UNION ALL
                        select 'Y'
                        from dual 
                    )