【问题标题】:Insert column from one table to other using Join使用 Join 将列从一个表插入到另一个表
【发布时间】:2018-01-28 03:32:14
【问题描述】:

我需要将 3 列从一个表插入到另一个表中,使用 JOIN by 3 个字段:姓名、姓氏和年龄

我需要使用 table_1 中的值更新 table_2 中的列状态、status1 和 status2

IF 

table_1.name = table_2.name
table_1.surname = table_2.surname
table_1.age= table_2.age

【问题讨论】:

    标签: sql-server join insert


    【解决方案1】:
    UPDATE t2
    SET 
     t2.[status]=t1.[status]
    ,t2.[status1]=t1.[status1]
    ,t2.[status2]=t1.[status2]
    FROM [table_1] t1
    INNER JOIN [table_2] t2 
    ON (t1.name=t2.name AND t1.surname=t2.surname AND t1.age=t2.age)
    

    正如你在 cmets 中提到的,这些表来自不同的数据库,那么请只更改两行之类的。

     FROM [yourDataBase1Name].[dbo].[table_1] t1
     INNER JOIN [yourDataBase2Name].[dbo].[table_2] t2
    

    【讨论】:

    • 它不起作用 :( 这两个表来自不同的数据库。也许这就是原因。因为我有错误消息 The multi-part identifier "database.table_2.staus" could not be bound
    • 如果它们来自 diff dbs,则完全不起作用。我将编辑我的答案
    【解决方案2】:

    只需使用 Join 更新表。 会是这样的:

    UPDATE t2
    SET t2.status = t1.status,
        t2.status1 = t1.status1,
        t2.status2 = t1.status2
    FROM t2 JOIN t1 on (t1.first_name = t2.first_name AND t1.last_name = t2.last_name AND t1.age = t2.age);
    

    查看这里了解更多信息:SQL update query using joins

    SQL 小提琴:http://sqlfiddle.com/#!3/b3951/1

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多