我有以下问题:
我有桌子:
TEST_TABLE
x_Id|y_Id
---------
2| 7
2| 8
3| 7
4| 7
5| 8
如果x_Id有y_Id(7)和y_Id(8),我想删除记录。如果y_Id = 8且y_Id(7)在唯一x_Id中不存在,则将y_Id更新为7.
x_Id和y_Id是复合键。
结果示例:
TEST_TABLE
x_Id|y_Id
---------
2| 7
3| 7
4| 7
5| 7
答案 0 :(得分:5)
删除重复项(x_Id同时存在y_Id的7和8)并更新所有剩余的y_Id,其中y_Id = 8
DELETE FROM TEST_TABLE t1 WHERE y_Id=8 AND EXISTS (SELECT * FROM TEST_TABLE WHERE x_Id=t1.x_Id AND y_Id=7)
UPDATE TEST_TABLE SET y_Id=7 WHERE y_Id=8
答案 1 :(得分:1)
这些查询不使用核心子查询(必须为外部查询的每一行执行它们),因此它们应该非常有效。
delete from test_table
where y_id = 8
and x_id in (select x_id from test_table where y_Id = 7);
update test_table set y_id = 7
where x_id in (select x_id from test_table where y_id = 8)
and x_id not in (select x_id from test_table where y_id = 7);