假设我有这张桌子 (简化后,我的查询涉及更多表格)
ConsignmentItem
ID |Item code| Name | Quantity
1 | 00000 | A | 3
2 | 11111 | B | 2
还有这张桌子
PickingItem
ID |ConsignmentID|Quantity
1 | 1 | 1
我的查询的作用是加入两个表并打印订购的产品数量和已注册的产品数量。我想得到下表
的结果Item Code| Name | Quantity_Ordered | Quantity_Registered
00000 | A | 3 | 1
11111 | B | 2 | 0
只要项目存在于“PickingItem”上,我的查询就会起作用,如果它不打印与上面一行相同的“Quantity_Registered”,使用我的查询得到的结果如下表所示
Item Code| Name | Quantity_Ordered | Quantity_Registered
00000 | A | 3 | 1
11111 | B | 2 | 1(this is wrong)
这是我正在使用的查询
SELECT C.Barcode AS 'Item Code',C.ProductName AS 'Name', C.Quantity AS 'Quantity_Ordered', ISNULL(P.Quantity,0) AS 'Quantity_Registered'
FROM PICKING.OrderPickingItem P
JOIN PICKING.OrderPicking OP ON P.PickingID = OP.PickingID
JOIN ORDERS.ConsignmentItem C ON OP.ConsignmentID = C.ConsignmentID
WHERE P.PickingID = 1 --For testing
任何人都知道我该怎么办,如果OrderPickingItem上不存在该产品,那么为该特定行设置P.Quantity = 0?
编辑: 表的结构
OrderPickingItem
PickingItemID PK
PickingID FK
ConsignmentItemID FK
Quantity
--other not used columns for this query
OrderPicking
PickingID PK
ConsignmentID FK
--other not used columns for this query
ConsignmentItem
ConsignmentItemID PK
ConsignmentID FK
Barcode
Quantity
ProductName
--other not used columns for this query
答案 0 :(得分:1)
您显然正在寻找外部联接:,即使没有匹配的选择,您也希望显示ConsignmentItem
条记录。
select
C.Barcode AS "Item Code",
C.ProductName AS "Name",
C.Quantity AS "Quantity_Ordered",
ISNULL(P.Quantity, 0) AS "Quantity_Registered"
from ORDERS.ConsignmentItem c
left join PICKING.OrderPicking op on OP.ConsignmentID = C.ConsignmentID
left join PICKING.OrderPickingItem P on P.PickingID = OP.PickingID
and P.ConsignmentItemID = C.ConsignmentItemID;
答案 1 :(得分:0)
对select子句中的数量执行外连接和ifnull(p.id,0)之类的操作。