MySQL根据条件UPDATE数据

时间:2022-09-08 16:34:20

1、第一种:使用b表数据更新a表

update Player as a ,PlayerSet as b

set a.role_id=b.set_value 

where a.role_id=b.set_key

2、第二种:也是使用b表数据更新a表,只是方法不一样

update RoleSet set_key=(SELECT name FROM Player where id = RoleSet.set_value); 
3、第三种:使用中间表,解决下面错误 Error Code: 1055. Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'xxxxxxx' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by(中文意思大概是:不能对同一张表进行同时读写)

(分享一个小技巧:使用变量增加不重复后缀) set @i:=1;
update Group 
SET name=CONCAT(name,'_', (@i:=@i+1))
where name in
(
SELECT a.GroupName
from
(
        SELECT name  as GroupName
        FROM Group 
        GROUP BY name 
        HAVING count(*) > 1
) as a
);