拥有以下示例数据:
Shipment table
Shipment_ID Readable_Shipment_ID
12345 ICanReadThis
Shipment_Detail table
Shpmnt_ID Shpmnt_Dtl_ID PO_ID PO_Dtl_ID1 Product_ID
12345 10000 11111 100 10203045
12345 10001 11111 110 10204589
12345 10002 11111 120 10205896
12345 10003 11111 130 10211212
12345 10004 11111 140 10305566
Purchase_Order_Detail table
PO_ID PO_Dtl_ID2 Product_ID2
11111 1 10203045
11111 2 10204589
11111 5 10305566
Purchase_Order_Detail table
PO_ID PO_Dtl_ID2 Product_ID2
11111 1 10203045
11111 2 10204589
11111 5 10305566
我正在尝试创建一个查询,该查询返回Shipment_Detail表中存在的Product_ID值列表,但在Purchase_Order_Detail表中不存在。
使事情复杂化的是我想使用人类可读出货号(Readable_Shipment_ID)作为输入,因为这是我作为起点给予的。
我已经想出了这个,它可以工作,但需要在Readable_Shipment_ID值中使用绑定变量或硬编码:
原谅任何语法错误,我仍然是SQL语言的新手。查询中的字段已更改为匿名查询。
我正在寻找一种方法来避免绑定变量':MySHP'并且我确定必须有一种方法可以使用我无法看到或不知道的其他联接或方法来重构此查询。
答案 0 :(得分:0)
这就是你要追求的吗?
Select Distinct SD.Product_ID
From
Shipment_Detail SD
join Shipment S on S.Shipment_ID = SD.Shpmnt_ID
left join Purchase_Order_Detail POD on POD.Product_ID2 = SD.Product_ID
Where
S.Readable_Shipment_ID = @YourParameter
and POD.Product_ID2 IS NULL
如果在Purchase_Order_Detail中不存在Product_ID,它将仅从Shipment_Detail返回Product_ID,并且只返回与您指定的Readable_Shipment_ID值相关的Product_ID