简体   繁体   English

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

[英]update table data if id exists in another table

I want to update mysql table data if id of a row exists in another table. 如果另一张表中存在一行ID,我想更新mysql表数据。

Table1 has a column called ID. 表1有一列称为ID。 Table2 also has the same column. 表2也有相同的列。 If there is a row which exists in both the table, it should be updated. 如果两个表中都存在一行,则应对其进行更新。

edit: I want to update every row in table1 whose ID exist in table2. 编辑:我想更新table1中ID在table2中存在的每一行。

Please help. 请帮忙。 Thanks in advance. 提前致谢。 By the way, I am using PHP. 顺便说一句,我正在使用PHP。

You can check if the row exists in the other table using a subquery: 您可以使用子查询来检查其他表中是否存在该行:

update table2 set xyz_column = 'some value'
where id = ?
and exists (select 1 from table1 where id = ?)

or simply: 或者简单地:

update table2 set xyz_column = 'some value'
where id = (select id from table1 where id = ?)

EDIT: 编辑:

As per the edit, ie if you want to update all rows of table1 for which id exists in table2, you can use update join: 根据编辑,即,如果要更新在table2中存在其ID的table1的所有行,则可以使用update join:

update table1 t1
  join table2 t2 on t1.id = t2.id
set t1.xyz_column = 'some value';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM