我有两个表的列名称为Department。当我同时更新table1中的department列时,它必须根据id更新表2中的列。 现在,我需要更新ID与部门匹配的那些记录。
update t1
set t1.dept=t2.dept
from table1 t1
inner join table2 t2
on t1.id=t2.id
答案 0 :(得分:0)
注意:我只是在这里使用了MySQL语法,因为您没有指定。如果您不使用MySQL,则需要适应自己的dbms。
有两种方法可以完成此操作。
使用子查询:
使用子查询相对简单:
a = input('Clubhouse location: ')
print("-".join(str(ord(char)) for char in a))
# --> 84-114-101-101-104-111-117-115-101
如果您只想偶尔执行此操作,这将非常方便,但是我真的看不到您为什么要这么做。
如果您有一张大桌子,这样做的效率也不高。
使用触发器:
我认为使用触发器会更好,因为您只需对其进行设置,然后它将在后台发挥作用:
update table2
set table2.dept = (
select table1.dept
from table1
where table1.id = table2.id
limit 1
)
-- We need this, because if we don't have
-- it then table2.dept will be null whenever
-- there is no entry in table1 with the same id
where 0 < (select count(*) from table2 where table2.id = table1.id)
;
您可以阅读有关MySQL triggers here的更多信息。触发器的类型更多,例如在插入或删除时触发的触发器。