选择查询INNER JOIN问题

时间:2016-08-19 17:31:07

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

我有两个表RequisitionsRequisitionDetails

申请表

+---------------+-----------------+
| 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

3 个答案:

答案 0 :(得分:2)

由于RequistionID = 1表中有两行RequistionDetails,它返回两次。由于返回的行是完全相同的,您只需将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

答案 1 :(得分:2)

你也可以使用exists for your

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
 )