SQL更新记录与另一个表中的记录进行比较

时间:2010-02-24 18:45:56

标签: sql sql-update

应该相当简单。

我有2张桌子。其中一个有table1(ID,name,other_id),另一个表有table2(id,name,group,..)

我希望table1.other_id与table2.id相同,基于两个表中名称字段中的数据。

2 个答案:

答案 0 :(得分:2)

UPDATE t1
SET t1.other_id = t2.id
FROM Table1 t1
    JOIN Table2 t2 ON t1.name = t2.name

这当然假设您没有多个具有相同“名称”的记录,否则您将如何判断具有给定名称的记录是否需要来自table2的ID。

答案 1 :(得分:0)

这应该这样做:

update table1 t1
set other_id = (
    select id
    from table2 t2
    where t2.name = t1.name )

如果table2有多个具有相同名称的记录,则会失败。

相关问题