加入问题

时间:2019-06-26 23:07:02

标签: sql postgresql join left-join

我在主要详细信息布局中有两个表。我希望仅在主表和明细记录满足条件的情况下才选择它们。但是我希望所有主表项目都不管是否存在详细记录。

我的表格如下: 主-库存物品

icmasterid  icdetailquantity    pomasterid
WAD110796               -900    NULL
WAD110796                  0    NULL
WAD110796                  0    119450
WAD110796                900    119347
WAD118808                  0    NULL
WAD118808                 34    NULL
WAD118942                  0    NULL
WAD118942                 59    NULL
WAD118942                  0    NULL
WAD118942                -59    NULL
WAD118942                 59    NULL

详细信息-库存行

SELECT inventoryitem.icmasterid,
       inventoryitem.icdescription,
       inventoryline.icdetailquantity,inventoryline.pomasterid
FROM  inventoryitem 
      LEFT OUTER JOIN inventoryline ON inventoryitem.icmasterid=inventoryline.icmasterid 
WHERE inventoryitem.icmasterid < 'WAD18' and inventoryitem.icmasterid like 'WAD%' 
ORDER BY inventoryitem.icmasterid

我的sql

and inventoryline.pomasterid <> ''

上面给出的是库存物品中的所有物品以及它们的相关库存行记录。

但是当我添加

icmasterid  ICdescription                      icdetailquantity   pomasterid
WAD110796   WM KIWI-KLIP 3 BEND (MZ3,4,&6)                  0   119450
WAD110796   WM KIWI-KLIP 3 BEND (MZ3,4,&6)                900   119347

我只有两行。

icmasterid     icdescription                      icdetailquantity  pomasterid
WAD110796      WM KIWI-KLIP 3 BEND (MZ3,4,&6)                    0  119450
WAD110796      WM KIWI-KLIP 3 BEND (MZ3,4,&6)                  900  119347
WAD118806-50   STROLLER VALENCE BACKDRP HINGE                  NULL NULL
WAD118808      IK STROL B DROP MOUNTING HDW                    NULL NULL
WAD118942      1" S-HOOK BAG 100                               NULL NULL

我需要的是

r

2 个答案:

答案 0 :(得分:2)

WHERE子句中的逻辑移至ON子句:

SELECT
    ii.icmasterid,
    ii.icdescription,
    ii.icdetailquantity,inventoryline.pomasterid
FROM inventoryitem ii
LEFT JOIN inventoryline il
     ON ii.icmasterid = il.icmasterid AND
        -- SUBSTRING(ii.icmasterid, 4, 2) < '18' AND
        ii.icmasterid LIKE 'WAD%' 
ORDER BY
    ii.icmasterid;

答案 1 :(得分:0)

基于蒂姆·比格莱森的回答,我想到了这一点。

SELECT
    ii.icmasterid,
    ii.icdescription,
    ii.icdetailquantity,inventoryline.pomasterid
FROM inventoryitem ii
LEFT JOIN inventoryline il
    ON ii.icmasterid = il.icmasterid AND and inventoryline.pomasterid <> ''
WHERE
    ii.icmasterid < 'WAD18' AND
    ii.icmasterid LIKE 'WAD%' 
ORDER BY
    ii.icmasterid;