在SQL中使用LEFT OUTER JOIN中的CASE语句

时间:2010-03-22 05:41:16

标签: sql oracle plsql left-join

我有一个场景,我想在外连接中打开两个不同的表。它是这样的: -

         select mytable.id, 
                yourtable.id
           from mytable
left outer join (case
                    when mytable.id = 2 then table2 
                      yourtable on table1.id = table2.id
                    else
                      table3 yourtable on table1.id = table3.id
                 end)

......但它不起作用。有什么建议吗?

3 个答案:

答案 0 :(得分:4)

使用(Oracle 9i +):

   SELECT mt.id, 
          COALESCE(yt1.id, yt2.id)
     FROM MYTABLE mt
LEFT JOIN YOURTABLE yt1 ON yt1.id = mt.id
                       AND yt.id = 2
LEFT JOIN YOURTABLE yt2 ON yt2.id = mt.id

答案 1 :(得分:3)

这是另一种可能性,虽然我没有在Oracle上尝试过它:

select mytable.id,  
       yourtable.id 
from table1 as mytable left outer join 
    (SELECT 2 AS tableid, *
     FROM table2
     UNION ALL
     SELECT 1, *
     FROM table3) as yourtable
    ON mytable.id = yourtable.id
    AND tableid = CASE WHEN mytable.id = 2 THEN 2 ELSE 1 END

答案 2 :(得分:1)

此查询将来自EMP表的记录连接到DEPT表或SPECIAL_OPS表,具体取决于EMP.DEPTNO的值......

SQL> select e.ename
  2         , e.job
  3         , e.deptno
  4         , coalesce(d.dname, s.dname) as dname
  5  from  emp e
  6        left outer join dept d
  7             on ( e.deptno = 30
  8                  and e.deptno = d.deptno )
  9        left outer join special_ops s
 10             on ( e.deptno != 30
 11                  and e.deptno = s.deptno )
 12  where e.deptno in (30,50)
 13  order by e.deptno, e.empno
 14  /

ENAME      JOB           DEPTNO DNAME
---------- --------- ---------- --------------
VAN WIJK   SALESMAN          30 SALES
PADFIELD   SALESMAN          30 SALES
BILLINGTON SALESMAN          30 SALES
SPENCER    MANAGER           30 SALES
CAVE       SALESMAN          30 SALES
HALL       CLERK             30 SALES
VERREYNNE  PLUMBER           50 SKUNKWORKS
FEUERSTEIN PLUMBER           50 SKUNKWORKS

8 rows selected.

SQL>

我在ON子句中将过滤器包含在EMP.DEPTNO中。如果表中的数据是独占的,那么这可能是不必要的(即DEPTNO = 30只能加入DEPT而DEPTNO = 50只能加入SPECIAL_OPS)。但是,如果标识符可以出现在两个表中,那么它也是明确的。此外,明确我们的意图始终是良好的做法。除了其他任何事情,我们无法确定未来的数据状态。