我有这个查询,该查询已经有一个表联接并且结果符合预期。他们匹配第一张桌子
SELECT
A.RH6001 as Referencia,
A.RH6002 as UAP,
A.RH6030 as ConsumoWeek01,
A.RH6031 as ConsumoWeek02,
IC130M.LLBLT1 as Stock,
0 as PecasPorCaixa
FROM AUTO.D805DATPOR.TRP060H AS A
LEFT JOIN AUTO.D805DATPOR.IC130M IC130M
ON A.RH6001 = IC130M.LLPPN AND
IC130M.LLSTLC =
CASE A.RH6002
WHEN 'UAP1' THEN 'M1'
WHEN 'UAP2' THEN 'M2'
WHEN 'UAP3' THEN 'M3'
WHEN 'UAP4' THEN 'M4'
WHEN 'UAP5' THEN 'M5'
WHEN 'UAP6' THEN 'M6'
WHEN 'UAPP' THEN 'PROTOS'
WHEN 'EXT' THEN 'EXTR'
END
WHERE (A.RH6001 Not Like 'FS%')
AND A.RH6030 <> 0
ORDER BY Referencia DESC')
哪个返回我1361行。
现在我有另一个查询
SELECT
YDAUREP.AUD5CD AS Referencia,
YDAUREP.AUQCON AS PecasPorCaixa
FROM
AUTO.YSACHAPOR.YDAUREP YDAUREP
WHERE (YDAUREP.AUD5CD Like 'M%'
AND YDAUREP.AUD5CD Not Like '%P%')
AND (YDAUREP.AUA0NB>1)
AND (YDAUREP.AUG6ST='O')
ORDER BY YDAUREP.AUD5CD'
返回785行
我想加入两个表,其中第二个表上的所有行都与第一个表匹配,基本上它应该返回1361行。
我必须使用列Referencia
来连接两个表,问题是它在第二个表上是唯一值,而在第一个表上则不是,我认为这是因为它没有返回预期的行。
这是两个表都已连接的查询:
SELECT
A.RH6001 as Referencia,
A.RH6002 as UAP,
A.RH6030 as ConsumoWeek01,
A.RH6031 as ConsumoWeek02,
IC130M.LLBLT1 as Stock,
YDAUREP.AUQCON AS PecasPorCaixa
FROM AUTO.D805DATPOR.TRP060H AS A
LEFT JOIN AUTO.D805DATPOR.IC130M IC130M
ON A.RH6001 = IC130M.LLPPN AND
IC130M.LLSTLC =
CASE A.RH6002
WHEN 'UAP1' THEN 'M1'
WHEN 'UAP2' THEN 'M2'
WHEN 'UAP3' THEN 'M3'
WHEN 'UAP4' THEN 'M4'
WHEN 'UAP5' THEN 'M5'
WHEN 'UAP6' THEN 'M6'
WHEN 'UAPP' THEN 'PROTOS'
WHEN 'EXT' THEN 'EXTR'
END
LEFT JOIN AUTO.YSACHAPOR.YDAUREP YDAUREP
ON YDAUREP.AUD5CD = A.RH6001
WHERE (A.RH6001 Not Like 'FS%')
AND A.RH6030 <> 0
AND (YDAUREP.AUD5CD Like 'M%'
AND YDAUREP.AUD5CD Not Like '%P%')
AND (YDAUREP.AUA0NB>1)
AND (YDAUREP.AUG6ST='O')
ORDER BY Referencia DESC'
我做错了什么,或者我不知道如何使用联接。
我正在进行左联接,返回的结果是579行,这意味着它返回了第二个表中与第一个表匹配的所有行,我认为左联接将执行相反的操作。
无论哪种方式,即使我使用Right Join,它也会返回相同的行...
我不确定,但是问题可能出在我添加的额外的where子句中。
我如何只用第二张表上匹配的数据来获得1361行?
其余的可以是NULL
...
答案 0 :(得分:2)
您在YDAUREP
中引用WHERE
而不处理NULL
,将LEFT JOIN
转换为隐式INNER JOIN
。将该部分移至ON
:
SELECT A.RH6001 AS Referencia,
A.RH6002 AS UAP,
A.RH6030 AS ConsumoWeek01,
A.RH6031 AS ConsumoWeek02,
IC130M.LLBLT1 AS Stock,
YDAUREP.AUQCON AS PecasPorCaixa
FROM AUTO.D805DATPOR.TRP060H AS A
LEFT JOIN AUTO.D805DATPOR.IC130M AS IC130M ON A.RH6001 = IC130M.LLPPN
AND IC130M.LLSTLC = CASE A.RH6002
WHEN 'UAP1' THEN 'M1'
WHEN 'UAP2' THEN 'M2'
WHEN 'UAP3' THEN 'M3'
WHEN 'UAP4' THEN 'M4'
WHEN 'UAP5' THEN 'M5'
WHEN 'UAP6' THEN 'M6'
WHEN 'UAPP' THEN 'PROTOS'
WHEN 'EXT' THEN 'EXTR'
END
LEFT JOIN AUTO.YSACHAPOR.YDAUREP AS YDAUREP ON YDAUREP.AUD5CD = A.RH6001
AND YDAUREP.AUD5CD LIKE 'M%'
AND YDAUREP.AUD5CD NOT LIKE '%P%'
AND YDAUREP.AUA0NB > 1
AND YDAUREP.AUG6ST = 'O'
WHERE A.RH6001 NOT LIKE 'FS%'
AND A.RH6030 <> 0
ORDER BY Referencia DESC;
我也删除了多余的括号,因为它们是不需要的。