如果Record不存在SQL,则加入NULL

时间:2017-09-26 16:20:31

标签: sql sql-server tsql left-join

我有一个查询从表CustomerDetails中选择客户,并将联接保留到另一个表(CustomerActivity)以获取其上次登录时间,最后将联接保留到另一个表({{1}获得他们最后一次打开的订单(如果适用)。我也有一个大的WHERE子句过滤这个数据

客户随时只能在OpenOrderDetails表中拥有一条记录。我的查询如下所示:

OpenOrderDetails

我的问题是此查询仅返回在SELECT CD.*, H.LastCustomerLoginTime, OD.OrderFiledDate, OD.OrderCompletedDate FROM CustomerDetails CD LEFT JOIN CustomerActivity H ON H.CustomerID = CD.CustomerID LEFT JOIN OpenOrderDetails OD ON CD.CustomerID = OD.CustomerID WHERE CD.OrderStatus IN (1,2,3) AND (CustomerType = 1 or (CustomerType = 3 and CustomerActive IN (1,2))) AND (OD.OrderFiledDate IS NULL OR CD.TimeStamp >= OD.OrderFiledDate) AND (OD.OrderCompletedDate IS NULL OR CD.TimeStamp <= OD.OrderCompletedDate) 表中有记录的客户记录。如何返回每个客户,OpenOrderDetails / OrderFiledDate(如果存在),如果OrderCompletedDate表中不存在该客户的记录,则为NULL?

2 个答案:

答案 0 :(得分:1)

将一些OpenOrderDetails条件移至join子句

 SELECT CD.*, H.LastCustomerLoginTime, OD.OrderFiledDate, OD.OrderCompletedDate
FROM CustomerDetails CD
LEFT JOIN CustomerActivity H ON H.CustomerID = CD.CustomerID 
LEFT JOIN OpenOrderDetails OD   ON CD.CustomerID = DLECS.CustomerID
                    AND (OD.OrderFiledDate IS NULL OR CD.TimeStamp >= OD.OrderFiledDate)
                    AND (OD.OrderCompletedDate IS NULL OR CD.TimeStamp <= OD.OrderCompletedDate)
WHERE CD.OrderStatus IN (1,2,3)
AND (CustomerType = 1 or (CustomerType = 3 and CustomerActive IN (1,2)))

答案 1 :(得分:1)

执行LEFT JOIN时,引用WHERE子句中的任何右侧表列会将其转换为INNER JOIN。要解决这个问题,只需删除引用&#34;右侧&#34;的任何和所有谓词。 WHERE子句中的列,并将它们移动到LEFT JOIN条件。

这些方面的东西......

SELECT
    CD.*, 
    H.LastCustomerLoginTime, 
    OD.OrderFiledDate, 
    OD.OrderCompletedDate
FROM
    CustomerDetails CD
    LEFT JOIN CustomerActivity H
        ON H.CustomerID = CD.CustomerID
    LEFT JOIN OpenOrderDetails OD
        ON CD.CustomerID = DLECS.CustomerID
        AND (   OD.OrderFiledDate IS NULL
            OR  CD.TimeStamp >= OD.OrderFiledDate
        )
        AND (   OD.OrderCompletedDate IS NULL
                OR  CD.TimeStamp <= OD.OrderCompletedDate
            )
WHERE
    CD.OrderStatus IN ( 1, 2, 3 )
    AND (
            CustomerType = 1
            OR  
            (   
                CustomerType = 3
                AND CustomerActive IN ( 1, 2 )
            )
        );