sql查询从两个表的组合创建新表

时间:2011-09-22 23:51:42

标签: sql tsql

我有一张表如下: 表1

temp_id    node_name  variable_1 variable_2 variable_3
1          ab         a          b           y
2          sdd        a          a           a
3          u          a          s           s

和另一个表如下: 表2

temp_id    node_name  variable_1 variable_2 variable_3
1          ab         as        sb           y
2          sdd        a          a           a
3          u          a          s           s

我想获取表1中的所有记录,其中表1的variable_1,variable_2和variable_3与表2不匹配。

我如何在TSQL中执行此操作?

2 个答案:

答案 0 :(得分:3)

试试这个:

INSERT INTO new_table
SELECT t1.* FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t1.temp_id = t2.temp_id AND 
   t1.node_name = t2.node_name
WHERE t1.variable_1 <> t2.variable_1 AND
      t1.variable_2 <> t2.variable_2 AND
      t1.variable_3 <> t2.variable_3

答案 1 :(得分:1)

SELECT * FROM [table 1] t1
WHERE NOT EXISTS (
    SELECT * FROM [table 2] t2
    WHERE
        t1.variable_1 = t2.variable_1
        AND t1.variable_2 = t2.variable_2
        AND t1.variable_3 = t2.variable_3
)

<强> --- --- EDIT

上面将“从表1中获取表1中variable_1,variable_2和variable_3与表2不匹配的所有记录”,如您所知。

但是,似乎您希望匹配表2中的特定行而不仅仅是任何行(BTW,您应该在您的问题中指定)。如果是这样的话,Marco的回答看起来不错。