SQL Server插入左连接

时间:2017-07-20 10:30:08

标签: sql sql-server

我有两张桌子:

    TABLE1                        TABLE2

COLUMN1 COLUMN2               COLUMN1 COLUMN2
---------------               ---------------
John      56                     45      A
Bob       45                     45      B 
Eva       68                     68      C
Alex      56                     47      D
Android   48                     45      L 
Mum       68                     68      C
…         …                      56      Q
                                  …     ...

我需要在一个表中添加列,事实上我将使用函数join从其他表插入新列值

COLUMN1 COLUMN2 COLUMN3
-----------------------
John      56      Q 
Bob       45      B 
Bob       45      A
Bob       45      L
Alex      56      Q
Eva       68      C
Android   48      NULL         
Mum       68      C
…         …        …     


ALTER TABLE [dbo].[Table1]
ADD Column3 NVARCHAR(255); 

INSERT INTO [dbo].[Table1] (column3)
    SELECT table2.column2
    FROM [dbo].[Table2] 
    LEFT JOIN [dbo].[table1] ON table1.column2 = table2.column1

但我得到了

COLUMN1 COLUMN2 COLUMN3
------------------------
John     56       
Bob      45       
Eva      68       
NULL     NULL     A
NULL     NULL     D
NULL     NULL     C
…         …       …

你能帮我修理插页吗?

2 个答案:

答案 0 :(得分:2)

我不知道left join与此有什么关系:

UPDATE t1
    SET column3 = t2.column2
    FROM [dbo].[Table1] t1 JOIN
         [dbo].[Table2] t2
         ON t1.column2 = t2.column1;

Table2中未找到的值将设置为NULL

编辑:

等一下。您正在将以及值插入。您似乎想要完成此查询:

SELECT t1.column1, t1.column2, t2.column3
FROM [dbo].[Table1] t1 LEFT JOIN
     [dbo].[Table2] t2
     ON t1.column2 = t2.column1;

我的建议是将其放入新表中,而不是Table1

SELECT t1.column1, t1.column2, t2.column3
INTO [dbo].[Table3]
FROM [dbo].[Table1] t1 LEFT JOIN
     [dbo].[Table2] t2
     ON t1.column2 = t2.column1;

如果您确实要替换Table1中的数据,请使用中间表:

SELECT t1.column1, t1.column2, t2.column3
INTO #temp
FROM [dbo].[Table1] t1 LEFT JOIN
     [dbo].[Table2] t2
     ON t1.column2 = t2.column1;

TRUNCATE TABLE dbo.Table1;

INSERT INTO dbo.Table1 (column1, column2, column3)
    SELECT column1, column2, column3
    FROM #temp;

答案 1 :(得分:1)

在我看来,你需要更新,而不是插入......请尝试这样做:

UPDATE t1 
SET column3 = t2.column2 
FROM dbo.Table2 t2
LEFT JOIN dbo.Table1 t1 ON t1.column2 = t2.column1