Sunday Lalbiaknia
Sunday Lalbiaknia

Reputation: 179

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.

Upvotes: 2

Views: 3184

Answers (1)

Gurwinder Singh
Gurwinder Singh

Reputation: 39467

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, i.e. 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';

Upvotes: 6

Related Questions