我正在尝试进行左联接,以便即使在第二个表中没有与之对应的值,我也将从表1中获得所有行。
我的结构是:
位置表:
ID LocName
1 Trk1
2 Trk2
3 Trk3
4 Unk
数量表:
ID PartID Quantity LocationID
1 1 2 1
2 3 12 2
3 2 6 1
4 6 8 3
5 6 5 1
我正在尝试加入,但也要查询特定的PartID。我的查询是:
SELECT
INV_LOCATIONS.ID AS LocationID,
INV_LOCATIONS.NAME AS LocationName,
INV_QUANTITY.QUANTITY AS Quantity
FROM INV_LOCATIONS
LEFT JOIN INV_QUANTITY ON INV_LOCATIONS.ID = INV_QUANTITY.LOCATION_ID
WHERE INV_QUANTITY.PART_ID = 1;
我现在的输出为:
ID LocName Quantity
1 Trk1 5
3 Trk3 8
所需的输出是:
ID LocName Quantity
1 Trk1 5
2 Trk2 NULL/0
3 Trk3 8
4 Unk NULL/0
我想是因为我有WHERE INV_QUANTITY.PART_ID = 1
,并且迫使它出现在数量表中。我需要能够验证它是否在正确的部分上,但是如果它不存在,如何将其包括在内。我知道我之前做过非常相似的事情,但是我不记得哪个项目,所以我找不到任何地方的代码。
您需要将过滤逻辑移至ON
子句:
SELECT il.ID AS LocationID, il.NAME AS LocationName,
iq.QUANTITY AS Quantity
FROM INV_LOCATIONS il LEFT JOIN
INV_QUANTITY iq
ON il.ID = iq.LOCATION_ID AND iq.PART_ID = 1;