How to return rows from left table not found in right table?

前端 未结 7 973
滥情空心
滥情空心 2020-12-23 09:09

I have two tables with similar column names and I need to return records from the left table which are not found in the right table? I have a primary key(column) which will

7条回答
  •  借酒劲吻你
    2020-12-23 09:45

    I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).

    DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
    DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))
    
    INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
    INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
    INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')
    
    
    INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
    INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')
    
    SELECT l.*
    FROM 
        @testLeft l
         LEFT JOIN 
        @testRight r ON 
            l.ID = r.ID
    WHERE r.ID IS NULL 
    

提交回复
热议问题