我可以在SQL中进行“条件”连接吗?

时间:2014-02-28 16:43:08

标签: sql db2

这是sceanrio ......

表格客户端

CLIENT     NAME
------     ----
123        Smith
456        Jones

表CLIENT_ADDRESS

CLIENT     ADDRESS
------     -------
000        100 MAIN ST  (this is a default address)
123        999 ELM ST

我希望我的结果集看起来像这样......

CLIENT     NAME     ADDRESS
------     ----     -------
123        Smith    999 ELM ST
456        Jones    100 MAIN ST   (pulls the default address since none found for client)

我可以在一次加入中执行此操作吗?

显然这个加入

SELECT A.CLIENT, A.NAME, B.ADDRESS
FROM CLIENT A
LEFT OUTER JOIN CLIENT_ADDRESS B
ON A.CLIENT = B.CLIENT

不会返回客户端456的默认地址。

如何更改此连接以实现此目的?

3 个答案:

答案 0 :(得分:2)

不在一个联接中,但有两个联接,并且合并

SELECT A.CLIENT, A.NAME, 
   coalesce(b.ADDRESS, d.Address) Address
FROM CLIENT A
    LEFT JOIN CLIENT_ADDRESS B
        ON A.CLIENT = B.CLIENT
    LEFT JOIN CLIENT_ADDRESS D
        ON d.CLIENT = '000'

答案 1 :(得分:2)

您需要另一个加入:

SELECT
     A.CLIENT
    ,A.NAME
    ,COALESCE(B.ADDRESS, C.ADDRESS)
FROM CLIENT A
LEFT JOIN CLIENT_ADDRESS B
  ON A.CLIENT = B.CLIENT
LEFT JOIN CLIENT_ADDRESS C
  ON C.CLIENT = '000'

答案 2 :(得分:0)

您需要更复杂的逻辑:

SELECT c.CLIENT, c.NAME, COALESCE(ca.ADDRESS, def.ADDRESS) as ADDRESS
FROM CLIENT c LEFT OUTER JOIN
     CLIENT_ADDRESS ca
     ON c.CLIENT = ca.CLIENT CROSS JOIN
     (SELECT ADDRESS FROM CLIENT_ADDRESS WHERE CLIENT = '000'
     ) as def;

即,在子查询中找到默认地址,然后在适当的位置选择。