2016-08-19 100 views
1

我拖表RequisitionsRequisitionDetails選擇查詢INNER JOIN問題

申請表

+---------------+-----------------+ 
| RequisitionID | RequisitionDate | 
+---------------+-----------------+ 
|    1 | 2016-08-17  | 
|    2 | 2016-08-18  | 
|    3 | 2016-08-19  | 
+---------------+-----------------+ 

RequisitionDetails表

+---------------------+---------------+--------+----------+------------------+ 
| RequisitionDetailID | RequisitionID | ItemID | Quantity | ReceivedQuantity | 
+---------------------+---------------+--------+----------+------------------+ 
|     1 |    1 |  1 |  2 |    1 | 
|     2 |    1 |  2 |  3 |    2 | 
|     3 |    2 |  3 |  4 |    3 | 
+---------------------+---------------+--------+----------+------------------+ 

我試圖讓申請數據,其中數量不等於ReceivedQuantity。

我已經嘗試了下面的查詢,但它的記錄是RequisitionID 1兩次。

如何使查詢返回申請單數據而不重複申請單數據基於數量不等於ReceivedQuantity的項目。

SELECT 
    dbo.Requisitions.RequisitionID, 
    dbo.Requisitions.RequisitionDate 
FROM dbo.Requisitions 
INNER JOIN dbo.RequisitionDetails 
    ON dbo.Requisitions.RequisitionID = dbo.RequisitionDetails.RequisitionID 
where dbo.RequisitionDetails.Quantity != dbo.RequisitionDetails.ReceivedQuantity 

回答

2

它在RequistionDetailsRequistionID = 1返回,因爲兩行的兩倍。由於返回的行是準確的重複,你可以在DISTINCT關鍵字簡單地添加到您的選擇,看看他們中的一個:

SELECT DISTINCT 
dbo.Requisitions.RequisitionID, 
dbo.Requisitions.RequisitionDate 
FROM dbo.Requisitions 
INNER JOIN dbo.RequisitionDetails 
ON dbo.Requisitions.RequisitionID = dbo.RequisitionDetails.RequisitionID 
where dbo.RequisitionDetails.Quantity!= 
dbo.RequisitionDetails.ReceivedQuantity 

你還應該使用一些別名來清理你的查詢:

SELECT DISTINCT 
      R.RequisitionID, 
      R.RequisitionDate 
FROM  dbo.Requisitions R 
INNER JOIN dbo.RequisitionDetails RD ON R.RequisitionID = RD.RequisitionID 
WHERE  RD.Quantity != RD.ReceivedQuantity 
2

你也可以使用存在的情況下

select 
* from requistions rq where exists(
select 1 from RequisitionDetails rd where rd.RequisitionID=rq.RequisitionID 
and rd.Quantity!=rd.ReceivedQuantity) 
2

因爲你不從第2表列需要你還可以切換到EXISTS避免DISTINCT

SELECT req.* 
FROM dbo.Requisitions as req 
WHERE EXISTS 
(SELECT * FROM dbo.RequisitionDetails as req_det 
    WHERE req.RequisitionID = req_det.RequisitionID 
     AND Quantity <> ReceivedQuantity 
) 

或者IN

SELECT req.* 
FROM dbo.Requisitions 
WHERE RequisitionID IN 
(SELECT RequisitionID 
    FROM dbo.RequisitionDetails 
    WHERE Quantity <> ReceivedQuantity 
)