简体   繁体   中英

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.

Table1 has a column called ID. Table2 also has the same column. 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.

Please help. Thanks in advance. By the way, I am using 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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