MS SQL不存在于更多列的位置

时间:2017-08-31 08:36:56

标签: sql sql-server sql-server-2008

我有表格1,我需要从表格2和广告到表格2只有不在表格2中的行

Table 1
ID  Name    N   T
A   Bob    33   Y
B   Eva    44   N
C   John   47   Y
B   Alex   44  N
D   Bob    47  Y

Table 2 
ID  Name   N   T
A   Bob    34  Y
B   Alex   44  N
D   Bob    47  Y

我尝试设置这种类型的版本脚本,但我得到整个表1 +新行的双重性

INSERT INTO TABLE_2
  (ID , Name ,  N ,  T)
SELECT table1.ID,  table1.Name,   table1.N,   table1.T
FROM TABLE_1 table1 
WHERE NOT EXISTS(SELECT 1
                 FROM TABLE_2 table2
                 WHERE (table2.ID = table1.ID) and (table2.Name = table1.Name) and (table2.N = table1.N )AND (table2.T =  table1.T))

期待结果

A   Bob    34   Y
B   Alex   44   N
D   Bob    47   Y
A   Bob    33   Y
B   Eva    44   N
C   John   47   Y

3 个答案:

答案 0 :(得分:0)

一种方法是使用选择查询INSERT INTO ... SELECT来识别table1中与table2中某些记录不完全匹配的所有记录。

INSERT INTO table2 (ID, Name, N, T)
SELECT t1.ID, t1.Name, t1.N, t1.T
FROM table1 t1
LEFT JOIN table2 t2
    ON t1.ID   = t2.ID   AND
       t1.Name = t2.Name AND
       t1.N    = t2.N    AND
       t1.T    = t2.T
WHERE t2.ID IS NULL

请注意,这里的逻辑是,如果table1中某个给定记录的一列与table2中的某个记录不一致,则连接将失败,并且所有{{1然后,列会在结果集中出现table2NULL子句仅限于WHERE中的此类非匹配记录。

答案 1 :(得分:0)

您可以使用左连接加入两个表。

必须插入Table_1中与Table_2不匹配的所有记录。要查看哪条记录没有匹配,您只需使用T2.ID IS NULL

即可
 INSERT INTO TABLE_2 (ID , Name ,  N ,  T)
      SELECT T1.ID
            ,T1.Name
            ,T1.N
            ,T1.T
        FROM TABLE_1 T1 
   LEFT JOIN TABLE_2 T2
          ON T1.ID    = T2.ID
         AND T1.Name  = T2.Name
         AND T1.N     = T2.N
         AND T1.T     = T2.T
       WHERE T2.ID IS NULL

答案 2 :(得分:0)

declare @Table1 table (ID varchar(100),  Name varchar(100),   N int,   T varchar(100));
insert into @Table1 values
('A',   'Bob',    33,   'Y'),
('B',   'Eva',    44,   'N'),
('C',   'John',   47,   'Y'),
('B',   'Alex',   44,  'N'),
('D',   'Bob',    47,  'Y')

declare @Table2 table (ID varchar(100),  Name varchar(100),   N int,   T varchar(100));
insert into @Table2 values
('A',   'Bob',    34,   'Y'),
('B',   'Alex',   44,  'N'),
('D',   'Bob',    47,  'Y')

insert into @Table2
select *
from @Table1 t1
where not exists (select * 
                  from @Table2 t2
                  where t2.ID = t1.ID and t2.N= t1.N and t2.Name = t1.Name and t1.T = t2.T);