我有 tableA
存储有关用户的信息,假设表中已保存一个用户 (UserA
),我想创建第二个用户 ( UserB
)复制UserA
拥有的数据。
我会做这样的事情:
Insert into tableA (userID, switch, plateType, groupVal, brokeage)
Select 'UserB', switch, plateType, groupVal, brokeage
from tableA
where userID = 'UserA';
没关系。
现在有时我必须读取 UserA
的数据,并用它更新 UserB
,但需要在上面的同一查询中执行此操作,所以我需要使用在重复的键上。
我已经写了这个,但它不起作用,我一直在研究,但找不到我需要的答案:
Insert into tableA (userID, switch, plateType, groupVal, brokeage)
Select 'UserB', switch, plateType, groupVal, brokeage
from tableA
where userID = 'UserA'
on duplicate key
Update tableA brokeage = (Select brokeage
from tableA
where userID = 'UserA')
where userID = 'UserB';
如果有人能看出这有什么问题,我将不胜感激。
最佳答案
使用这个:
Insert into tableA (userID, switch, plateType, groupVal, brokeage)
Select 'UserB', switch, plateType, groupVal, brokeage
from tableA
where userID = 'UserA'
on duplicate key Update brokeage = (
Select brokeage
from tableA
where userID = 'UserA');
查看更新结构,它会更新重复行,无需精确表名的位置。
关于mysql - 使用 select 插入重复更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21382750/