views:

145

answers:

2

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.

A: 

What problem are you having, exactly?

Noon Silk
I just need to set related_id to NULL when related_id doesn't exist in related_table as id.
tomp
Ah, well cletus is correct then.
Noon Silk
+1  A: 
UPDATE table1 t
SET related_id = NULL
WHERE NOT EXISTS (SELECT 1 FROM related_table WHERE id = t.related_id)
cletus
Thanks.        
tomp