SQL可选的JOIN

时间:2018-10-11 00:00:35

标签: sql sql-server join

我有以下SQL语句:

SELECT
    invoice.id         "Invoice ID",
    account.name       "Owner"
FROM
    invoice
LEFT OUTER JOIN account 
    on invoice.customerid = account.id

但是,invoice.customerid可以是客户或联系人。这由发票表中的另一个字段(客户类型)决定。

那么如何根据另一列的值将JOIN更改为JOIN到每行的不同表?

使用MS SQL Server。

3 个答案:

答案 0 :(得分:1)

我会这样:

SELECT i.id as Invoice_ID,
       COALESCE(a.name, c.name) as Owner
FROM invoice i LEFT JOIN
     account a
     ON i.customerid = a.id AND i.customerType = 'Account' LEFT JOIN
     contact c
     ON i.customerid = c.id AND i.customerType = 'Contact';

请注意,这将customerType逻辑合并到ON子句中。这样可以使JOIN更准确。

答案 1 :(得分:0)

您可以在联接条件中使用CASE

    SELECT invoice.id   "Invoice ID",
       IsNull(account.NAME,contact.NAME) "Owner"
    FROM   invoice
       LEFT OUTER JOIN account
                    ON account.id = CASE
                                      WHEN invoice.customertype = 'Account'
                                        THEN invoice.customerid
                                      ELSE NULL
                                    END 
       LEFT OUTER JOIN contact
                    ON contact.id = CASE
                                      WHEN invoice.customertype = 'contact'
                                        THEN invoice.customerid
                                      ELSE NULL
                                    END 

答案 2 :(得分:0)

我假设您需要加入另一个表“联系人”,并且您只想根据customertype列的值返回客户名或联系人名。我假设customertype是一个字符串,在下面可能是'account'或'contact':

SELECT
    invoice.id 'Invoice ID',
    CASE invoice.customertype  
      WHEN 'account' THEN account.name
      WHEN 'contact' THEN contact.name   
    END 'Owner'
FROM
    invoice
LEFT OUTER JOIN account 
    ON invoice.customerid = account.id
LEFT OUTER JOIN contact
    ON invoice.customerid = contact.id