UPDATE表SET related_id = NULL WHERE related_id在相关表中不存在

时间:2009-08-15 11:22:56

标签: mysql

我需要更新 table 并设置 table related_id (将 related table “绑定”表格的列)到NULL table related_id <{em> related_table related_table id

示例:

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

我需要的查询应该像这样更新 table

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

(因为 <{1}} id 36和43

请帮助。

1 个答案:

答案 0 :(得分:1)

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