I have a mapping table with a unique contraint on the tuple (c_id, t_id)
.
Here's some sample data to illustrate the situation:
id c_id t_id
----------------
1 10 2
2 10 3
3 10 7
4 12 2
5 13 3
I wrote a merge function for t_ids
(x,y -> z OR x,y -> x).
If my content (c_id
) has both t_ids
, then I'm of course violating the constraint by using this statement:
UPDATE mapping_table
SET t_id = '$target_tid'
WHERE t_id = '$t1_id' OR t_id = '$t2_id';
The result would be:
id c_id t_id
----------------
1 10 4
2 10 4 /* violates unique constraint */
3 10 7
Now I came up with this:
/* delete one of the duplicate entries */
DELETE FROM mapping_table
WHERE ( SELECT count(c_id)
FROM mapping_table
WHERE t_id = '$t1_id' OR t_id = '$t2_id'
) > 1;
/* update the remaining row */
UPDATE mapping_table
SET t_id = '$target_tid'
WHERE t_id = '$t1_id' OR t_id = '$t2_id';
Now I'm getting the following error:
You can't specify target table 'mapping_table' for update in FROM clause
My questions are:
- What's exactly wrong here? Is the
DELETE
statement seen as an update and cannot be used in theWHERE
clause? - This there any more efficient way to do this?