这将update
“YYY”而不是“ZZZ”通过使用not exists()
作为where
子句的一部分,以确保具有相同name
一排已经为xyId = 300
记录不存在。
update t
set xyId = 300
where xyId = 200
and not exists (
select 1
from t as i
where i.name = t.name
and i.xyId = 300
);
如果你想delete
行与xyId = 200
有与xyId = 300
相应的记录,你可以使用exists()
像这样:
delete
from t
where xyId = 200
and exists (
select 1
from t as i
where i.name = t.name
and i.xyId = 300
);
rextester演示:http://rextester.com/IIQL1351
结果从更新:
+----+------+------+
| id | name | xyId |
+----+------+------+
| 1 | xxx | 100 |
| 2 | yyy | 300 |
| 3 | zzz | 300 |
| 4 | zzz | 200 |
+----+------+------+
个
结果从删除:
+----+------+------+
| id | name | xyId |
+----+------+------+
| 1 | xxx | 100 |
| 2 | yyy | 300 |
| 3 | zzz | 300 |
+----+------+------+
嗯即时得到零行更新..好像你的逻辑是正确的,但。 – user1336827
@ user1336827我的查询中有一个错字,很抱歉 – SqlZim