如果 id 存在于另一个表中则更新表数据

Sun*_*nia 2 php mysql

如果行的 id 存在于另一个表中,我想更新 mysql 表数据。

Table1 有一个名为 ID 的列。表2也有相同的列。如果两个表中都存在某行,则应更新该行。

编辑:我想更新 table1 中 ID 存在于 table2 中的每一行。

请帮忙。提前致谢。顺便说一句,我正在使用 PHP。

Gur*_*ngh 6

您可以使用子查询检查该行是否存在于另一个表中:

update table2 set xyz_column = 'some value'
where id = ?
and exists (select 1 from table1 where id = ?)
Run Code Online (Sandbox Code Playgroud)

或者简单地:

update table2 set xyz_column = 'some value'
where id = (select id from table1 where id = ?)
Run Code Online (Sandbox Code Playgroud)

编辑:

根据编辑,即如果您想更新 table2 中存在 id 的 table1 的所有行,您可以使用 update join:

update table1 t1
  join table2 t2 on t1.id = t2.id
set t1.xyz_column = 'some value';
Run Code Online (Sandbox Code Playgroud)