【问题标题】:How to update ID column in table 1 from table 2 using Type in SQL?如何使用 SQL 类型从表 2 更新表 1 中的 ID 列?
【发布时间】:2021-02-06 16:35:00
【问题描述】:

这里以表 1 为例

      ID       Type        Description
------------ ------------ --------------
       5          A          abc 
       6          B          xyz 
       7          C          rst
       8          D          lne

这是表2:

      JID       Type     TDescription
------------ ------------ --------------
       1          A          123 
       2          B          456 
       3          C          789
       4          D          357

所以我想通过匹配它们的类型来更新表 1,但只是使用表 2 的 ID 列。

预期更新的表格:

      ID       Type        Description
------------ ------------ --------------
       1          A          abc 
       2          B          xyz 
       3          C          rst
       4          D          lne

我不确定如何使用另一个表的列来更新表的单列以匹配行。

【问题讨论】:

  • MySQL 还是 SQL Server?请仅标记一个数据库。更新语句的语法通常依赖于数据库。

标签: mysql sql-server sql-update inner-join


【解决方案1】:

一个选项使用子查询:

update table1
set id = (select t2.jid from table2 t2 where t2.type = table1.id)

这种语法应该在 MySQL 和 SQL Server 中都可以使用。

但是请注意,它将设置为table1null ids,其typetable2 中不存在。如果你想避免这种情况,使用 update/join 语法会更简单。

在 MySQL 中:

update table1 t1
inner join table2 t2 on t2.type = t1.type
set t1.id = t2.jid

在 SQL Server 中:

update t1
set t1.id = t2.jid
from table1 t1
inner join table2 t2 on t2.type = t1.type

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2012-10-20
    • 2021-09-29
    • 1970-01-01
    • 2021-02-27
    • 2017-04-25
    相关资源
    最近更新 更多