条件左连接SQL

时间:2017-12-07 08:53:41

标签: sql oracle

table A 
    ----------------------------
    NAME   | CODE  | BRANCH
    ----------------------------
    bob    | PL    | B
    david  | AA    | B
    susan  | PL    | C
    joe    | AB    | C
    alfred | PL    | B

table B 
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    PL   | code 1
    PB   | code 2 
    PC   | code 3

table C 
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    AA   | code 4
    AB   | code 5 
    AC   | code 6

有没有办法连接表A,B和C.而不加入所有表?

select A.*, COALESCE(B.DESCRIPTION, C.DESCRIPTION) AS DESCRIPTION  from A 
left join B on A.CODE = B.CODE
left join C on A.CODE = C.CODE

在我的实际案例中,将有超过10个加入同一列。 所以我需要有条件的左连接,类似这样的

SELECT A* , DESCRIPTION
FROM A  LEFT JOIN (
     CASE
        WHEN A.CODE = 'B' THEN SELECT * FROM B
        WHEN A.CODE = 'C' THEN SELECT * FROM C
      END  
    ) BC ON A.CODE = BC.CODE 

2 个答案:

答案 0 :(得分:1)

您无法使用CASE来实施流量控制。在SQL CASE中是一个返回单个值的表达式。

您可以使用以下查询:

select A.*, 
       CASE A.BRANCH
          WHEN 'B' THEN B.DESCRIPTION
          WHEN 'C' THEN C.DESCRIPTION
       END AS DESCRIPTION  
from A
left join B on A.CODE = B.CODE AND A.BRANCH = 'B'
left join C on A.CODE = C.CODE AND A.BRANCH = 'C'

答案 1 :(得分:0)

您可以使用它来生成查询。然后编写一个PL / SQL块来循环遍历所有这些查询并动态执行以便为您提供单独的结果。

SELECT    'SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN '
       || CASE WHEN A.BRANCH = 'B' THEN 'TABLEB B' END
       || CASE WHEN A.BRANCH = 'C' THEN 'TABLEC C' END
       || ' ON '
       || 'A.CODE = '
       || CASE WHEN A.BRANCH = 'B' THEN 'B.CODE' END
       || CASE WHEN A.BRANCH = 'C' THEN 'C.CODE' END
          v_query
  FROM TableA A;

<强>输出

V_QUERY                                                                         
--------------------------------------------------------------------------------
SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE   



SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE   



SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEC C ON A.CODE = C.CODE   



SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEC C ON A.CODE = C.CODE   



SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE