【问题标题】:Select Certain Column from Table1 and Insert to Certain Column in Table2 with Where Clause Conditions从表 1 中选择某列并使用 Where 子句条件插入到表 2 中的某列
【发布时间】:2019-03-15 06:17:42
【问题描述】:

表 1

|Id|Category_Id|Type_Id|Code|
+--+-----------+-------+----+
|1 |1          |1      |A   |
|3 |2          |1      |B   |
|4 |1          |3      |C   |

表2

|Id|Category_Id|Type_Id|Code_Id|
+--+-----------+-------+-------+    
|1 |1          |1      |NULL   |
|3 |2          |1      |NULL   |
|5 |9          |7      |NULL   |

如您所见,Table2 中的“Code_Id”列为 NULL。我需要使用 Table1 中“Id”列中的值更新该列,条件是 Table1 中“Category_Id”和“Type_Id”列中的值与 Table2 中“Category_Id”和“Type_Id”列中的值匹配。

我该怎么做呢?谢谢你,期待你的帮助。

【问题讨论】:

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


    【解决方案1】:

    使用加入更新

    update t2 set code_id=t1.id
    from table2
    join table1 t1 on t1.type_id=t2.type_id and t1.category_id=t2.category_id
    

    【讨论】:

    • 谢谢。这行得通。我试图接受这个答案,但网站一直告诉我,我可以在 5 分钟内接受答案。无论如何,谢谢你的热心帮助。 :)
    【解决方案2】:

    使用连接

    UPDATE t2
    SET Code_Id = t1.Id
    FROM Table2 t2
    JOIN Table1 t1 on t2.Type_Id=t1.Type_Id and t2.Category_Id=t1.Category_Id
    

    【讨论】:

      【解决方案3】:

      它必须像集合一样在所有条件下都需要别名,因为在多个表中可能是相同的列名而不是出现错误。

      UPDATE A 
      set A.code_id = B.id
      FROM table2 A
      INNER JOIN table1 B on B.type_id=A.type_id and B.category_id=A.category_id
      

      【讨论】:

        猜你喜欢
        • 2015-05-16
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        • 2020-10-01
        • 1970-01-01
        • 2015-02-28
        • 1970-01-01
        相关资源
        最近更新 更多