首页 > 解决方案 > 如何在不重复的情况下更新

问题描述

我有一张桌子

ID 姓名 类型
1 一种 15
2 一种 14
3 C 14
4 C 15
5 d 15
6 F 14
7 G 15

我想将 type = 15 的所有位置更新为 14。但是已经有一些同名的类型 14 我怎样才能只更新不同的

标签: sql

解决方案


如果您想避免会产生重复的更新行,您可以not exists使用update

update t
    set type = 14
    where type = 15 and
          not exists (select 1
                      from t t2
                      where t2.name = t.name and t2.type = 14
                     );

推荐阅读