LEFT JOIN并找到缺失的值

时间:2017-01-20 01:30:14

标签: sql sql-server stored-procedures

我试图找到一些帮助来完成这个功能。我试图列出SERIAL_NUMBER表中oL表中不存在的包含特定值的所有rL项。

以下是我提出的代码,但还没有进一步说明。无论我怎么写它,我总是生成所有存在的SERIAL_NUMBER项或根本没有。

DECLARE @val int
SET @val = 43770

SELECT oL.SERIAL_NUMBER 
FROM 
    ROBOTICS_OPTICS_UAT.dbo.AOF_ORDER_OPTICS AS oL 
    LEFT JOIN ROBOTICS_OPTICS_UAT.dbo.AOF_OPTIC_RESULTS AS rL 
        ON oL.SERIAL_NUMBER != rL.SERIAL_NUMBER
WHERE oL.SO_LINE_NUMBER = @val;

我在这里做错了什么?此代码生成oL.SO_LINE_NUMBER = @val的所有结果。我需要 - 减去rL表中已存在的序列号。

我也尝试过添加

WHERE rl.SERIAL_NUMBER IS NULL

但这不会产生任何效果。

4 个答案:

答案 0 :(得分:4)

除了弗拉基米尔回答,你只是搞乱了加入条件和过滤条件。

但是,如果值在行中重复,则需要注意join的乘数效应。如果您只想查看是否存在,可以使用Not Null

EXISTS

答案 1 :(得分:2)

您的查询看起来几乎正确。

您应该加入oL.SERIAL_NUMBER = rL.SERIAL_NUMBER(不是!=),然后只留下rL.SERIAL_NUMBER IS NULL的行。此过滤条件表示rL中没有行SERIAL_NUMBER

DECLARE @val int;
SET @val = 43770;

SELECT 
    oL.SERIAL_NUMBER 
FROM 
    ROBOTICS_OPTICS_UAT.dbo.AOF_ORDER_OPTICS AS oL 
    LEFT JOIN ROBOTICS_OPTICS_UAT.dbo.AOF_OPTIC_RESULTS AS rL
        ON oL.SERIAL_NUMBER = rL.SERIAL_NUMBER
WHERE 
    oL.SO_LINE_NUMBER = @val
    AND rL.SERIAL_NUMBER IS NULL
;

答案 2 :(得分:1)

你可以写一个这样的子查询:

DECLARE @val int;
SET @val = 43770;

SELECT 
    oL.SERIAL_NUMBER 
FROM 
    ROBOTICS_OPTICS_UAT.dbo.AOF_ORDER_OPTICS AS oL 
WHERE 
    oL.SO_LINE_NUMBER = @val
    AND oL.SERIAL_NUMBER NOT IN (
      SELECT rL.SERIAL_NUMBER
      FROM ROBOTICS_OPTICS_UAT.dbo.AOF_OPTIC_RESULTS AS rL
    )
;

答案 3 :(得分:0)

使用这个:  select ol.SERIAL_NUMBER from aof_order_optics ol where ol.SERIAL_NUMBER not in(select rl.SERIAL_NUMBER from aof_optic_results rl) and ol.SO_LINE_NUMBER=@val;