Mysql – UPDATE table SET related_id=NULL WHERE related_id doesn’t exist in related table

MySQL

I need to update table and set table.related_id (column that "binds" the table with related table) to NULL where the table.related_id doesn't exist in the related_table as related_table.id.

example:

TABLE:
----------------------
id | name | related_id
----------------------
1  | aaa  | 15
2  | bbb  | 36
3  | ccc  | 7
4  | xxx  | 43

RELATED_TABLE:
----------
id | name
----------
9  | ddd
15 | eee
7  | fff

The query I need is supposed to update table like that:

TABLE:
----------------------
id | name | related_id
----------------------
1  | aaa  | 15
2  | bbb  | NULL
3  | ccc  | 7
4  | xxx  | NULL

(because id 36 and 43 doesn't exist in related_table)

Please, help.

Best Answer

UPDATE table1 t
SET related_id = NULL
WHERE NOT EXISTS (SELECT 1 FROM related_table WHERE id = t.related_id)
Related Topic