Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使用条件更新表_Sql_Sql Server 2008 - Fatal编程技术网

Sql 使用条件更新表

Sql 使用条件更新表,sql,sql-server-2008,Sql,Sql Server 2008,我有以下问题: 我有一张桌子: TEST_TABLE x_Id|y_Id --------- 2| 7 2| 8 3| 7 4| 7 5| 8 如果x_Id有y_Id7和y_Id8,我想删除记录。如果y_Id=8且唯一x_Id中不存在y_Id 7,则将y_Id更新为7 x_Id和y_Id是复合密钥 结果示例: TEST_TABLE x_Id|y_Id --------- 2| 7 3| 7 4| 7 5|

我有以下问题:

我有一张桌子:

TEST_TABLE
x_Id|y_Id
---------
   2|   7
   2|   8
   3|   7
   4|   7
   5|   8
如果x_Id有y_Id7和y_Id8,我想删除记录。如果y_Id=8且唯一x_Id中不存在y_Id 7,则将y_Id更新为7

x_Id和y_Id是复合密钥

结果示例:

TEST_TABLE
x_Id|y_Id
---------
   2|   7
   3|   7
   4|   7
   5|   7

删除x_Id中同时存在y_Id的7和8的重复项,并更新y_Id=8的所有剩余y_Id

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

这些查询不使用corelated子查询,因为它们必须对外部查询的每一行执行,所以它们应该非常有效

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);

您是否能够编写一个select,其中x_Id有y_Id7和y_Id8,并且只是在删除时遇到问题?如果是这样,请发布您到目前为止所做的。您是否看过SQL Server中的执行计划?检查UPDATE语句,然后从TEST_TABLE x中检查可选的UPDATE TEST_TABLE SET y_Id=7,其中y_Id=8且不存在。从TEST_TABLE中选择*y_Id=7和x_Id=x。x_Id子句会导致嵌套循环,使用EXISTS子句可以防止嵌套循环。添加一件事:第二个WHERE条件是不必要的,因为删除满足此条件的行