查询不返回任何记录

时间:2016-07-06 11:10:08

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

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

所以我创建了以下架构。

模式

Schema

问题是当UserIDPurchaseOrders表中的Deliveries列具有不同的值时,查询不返回任何记录。

查询

SELECT
  dbo.Users.FirstName,
  dbo.Users.LastName,
  dbo.PurchaseOrders.PurchaseOrderDate,
  dbo.Deliveries.ExpectedDeliveryDate,
  dbo.Deliveries.ActualDeliveryDate
FROM dbo.PurchaseOrders
INNER JOIN dbo.Users
  ON dbo.PurchaseOrders.UserID = dbo.Users.UserID
INNER JOIN dbo.Deliveries
  ON dbo.PurchaseOrders.PurchaseOrderID = dbo.Deliveries.PurchaseOrderID
  AND dbo.Users.UserID = dbo.PurchaseOrders.UserID
  AND dbo.Users.UserID = dbo.Deliveries.UserID

2 个答案:

答案 0 :(得分:3)

您需要两个不同的联接Users。您还需要学习使用表别名:

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 p.UserID = pu.UserID JOIN
     dbo.Users du
     ON d.UserId = du.UserId;

由于这种情况,您的查询不会返回任何记录:

  AND dbo.Users.UserID = dbo.PurchaseOrders.UserID
  AND dbo.Users.UserID = dbo.Deliveries.UserID

这显然意味着dbo.PurchaseOrders.UserID = dbo.Deliveries.UserID。所以,如果不是这样,那么没有记录符合条件。

答案 1 :(得分:1)

使用内部联接时,如果数据不匹配,则不会获得任何记录。您需要使用LEFT JOIN,并且第二个连接不需要具有用户ID的条件。请尝试以下查询。

SELECT
dbo.Users.FirstName,
  dbo.Users.LastName,
  dbo.PurchaseOrders.PurchaseOrderDate,
  dbo.Deliveries.ExpectedDeliveryDate,
  dbo.Deliveries.ActualDeliveryDate
FROM dbo.PurchaseOrders
INNER JOIN dbo.Users
  ON dbo.PurchaseOrders.UserID = dbo.Users.UserID
LEFT JOIN dbo.Deliveries
  ON dbo.PurchaseOrders.PurchaseOrderID = dbo.Deliveries.PurchaseOrderID