从多个表中检索记录问题

时间:2016-07-15 15:10:42

标签: sql sql-server sql-server-2008

您好我正在制作购买订单的架构这些订单可以由特定用户订购,然后由其他用户接收。

问题是当Deliveries表中的UserID值为null时,查询返回没有记录。

UserID值为null,因为订单尚未交付。

查询

SELECT pu.FirstName as purchase_FirstName, pu.LastName as purchase_LastName,
       du.FirstName as delivery_FirstName, du.LastName as delivery_LastName,
       po.PurchaseOrderDate,
       d.ExpectedDeliveryDate, d.ActualDeliveryDate
FROM dbo.PurchaseOrders po JOIN
     dbo.Deliveries d
     ON po.PurchaseOrderID = d.PurchaseOrderID JOIN
     dbo.Users pu
     ON po.UserID = pu.UserID JOIN
     dbo.Users du
     ON d.UserId = du.UserId;

模式

enter image description here

1 个答案:

答案 0 :(得分:3)

你很可能在这里需要LEFT JOIN。一点格式化使这更容易阅读。您可以查看本文以了解不同类型的连接。 http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

SELECT pu.FirstName as purchase_FirstName
    , pu.LastName as purchase_LastName
    , du.FirstName as delivery_FirstName
    , du.LastName as delivery_LastName
    , po.PurchaseOrderDate
    , d.ExpectedDeliveryDate
    , d.ActualDeliveryDate
FROM dbo.PurchaseOrders po 
JOIN dbo.Users pu ON po.UserID = pu.UserID 
left JOIN dbo.Deliveries d ON po.PurchaseOrderID = d.PurchaseOrderID 
left JOIN dbo.Users du ON d.UserId = du.UserId;