I have a query that selects customers from a table CustomerDetails, and left joins onto another table (CustomerActivity) to get their last login time and finally left joins onto another table (OpenOrderDetails) to get their last open order (if applicable). I also have a big WHERE clause filtering this data
A customer can only have one record in the OpenOrderDetails table at anytime. My query looks like the following:
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) My issue is that this query only returns customer records that have a record in the OpenOrderDetails table. How do I return every customer, and OrderFiledDate/OrderCompletedDate if present, and NULL if a record for that customer does not exist in the OpenOrderDetails table?
customerTypeandCustomerActive? This is a common order of operations issue. You want the filters on tables being left joined to occur as part of the join. If they occur in the where clause the LEFT join then behaves like an inner join. Logically the tables are joined. The where clause then eliminates values not matching the criteria; including NULLS generated by the left join. The is null check on OD is a less common but acceptable approach to keeping the values from the left join, which is why I asked about CustomerActive and CustomerType.customerTypeorCustomerActiveisn't in customerDetails. and it too would need to be moved into the join or have the is null check.DLECS.CustomerIDon the 2nd left join? Shouldn't it beOD.CustomerID? Alias/table DLECS doesn't exist in the query as defined.