根据比较两列,在table1中查找不在table2中的行

时间:2017-11-29 20:09:50

标签: sql-server join

我有两个有3列的表。我想比较两个表中的两列,以查找第一列中的行而不是另一列中的行。到目前为止,我在两列上使用LEFT JOIN。我在带有垃圾数据的临时表上进行了测试,但该方法有效,但我的生产数据集有很多行,所以我无法验证它是否真的有效。

CREATE TABLE table1(
    [Timestamp] [date],
    [name] [varchar](50) NULL,
    [value] [varchar](50) NULL
)

CREATE TABLE table2(
    [Timestamp] [date],
    [name] [varchar](50) NULL,
    [value] [varchar](50) NULL
)

INSERT INTO table1 VALUES ('2017-09-10', 'a', 'one'),
('2017-01-19', 'a', 'two'),
('2016-12-07', 'a', 'three'),
('2016-11-15', 'b', 'four'),
('2016-10-19', 'b', 'five'),
('2017-07-09', 'b', 'six'),
('2016-01-31', 'c', 'seven'),
('2016-12-15', 'd', 'eight');

INSERT INTO table2 VALUES ('2016-12-15', 'a', 'two'),
('2016-06-20', 'b', 'four'),
('2017-04-09', 'b', 'five'),
('2016-03-03', 'b', 'six'),
('2016-03-24', 'c', 'seven'),
('2016-07-04', 'e', 'nine'),
('2016-10-24', 'f', 'ten'),
('2016-11-06', 'g', 'eleven')

SELECT * FROM table1

    | Timestamp  | name | value | 
    |------------|------|-------| 
    | 2017-09-10 | a    | one   | 
    | 2017-01-19 | a    | two   | 
    | 2016-12-07 | a    | three | 
    | 2016-11-15 | b    | four  | 
    | 2016-10-19 | b    | five  | 
    | 2017-07-09 | b    | six   | 
    | 2016-01-31 | c    | seven | 
    | 2016-12-15 | d    | eight | 

SELECT * FROM table2

    | Timestamp  | name | value  | 
    |------------|------|--------| 
    | 2016-12-15 | a    | two    | 
    | 2016-06-20 | b    | four   | 
    | 2017-04-09 | b    | five   | 
    | 2016-03-03 | b    | six    | 
    | 2016-03-24 | c    | seven  | 
    | 2016-07-04 | e    | nine   | 
    | 2016-10-24 | f    | ten    | 
    | 2016-11-06 | g    | eleven | 

SELECT table1.name, table1.value, IIF(table2.Timestamp IS NULL, 'missing', 'not missing') AS 'status' FROM table1 LEFT JOIN table2 ON table1.name = table2.name AND table1.value = table2.value

    | name | value | status      | 
    |------|-------|-------------| 
    | a    | one   | missing     | 
    | a    | two   | not missing | 
    | a    | three | missing     | 
    | b    | four  | not missing | 
    | b    | five  | not missing | 
    | b    | six   | not missing | 
    | c    | seven | not missing | 
    | d    | eight | missing     | 

DROP TABLE table1
DROP TABLE table2

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上。您只需要测试右侧值是否为null,以确定是否没有匹配项。为了获得最佳性能,您需要在名称&上编制索引。两个表中的值。

SELECT  table1.name,
        table1.value
  FROM  table1
  LEFT OUTER JOIN table2
    ON table1.name = table2.name
    AND table1.value = table2.value
  WHERE table2.value IS NULL