mysql - 使用 select 插入重复更新

标签 mysql

我有 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/

相关文章:

PHP & MySQL 数据库显示多张图片

php - 在具有 30,000 条记录的 mysql 表中查找数据

mysql - 选择包含希伯来字母的列

mysql - 无法使用临时表添加或更新子行错误?

mysql - 查找两个表中的最大记录

mysql - 当我在 MySQL 中使用 'select' 时,如何将表中的所有日期放入新列中?

c# - 从 C# 运行 MySQL 命令时忽略 @ 符号

php - 从一个到多个模态获取 id - Laravel

php - 检查行mysql中的值

php - PHP中如何隐藏多个链接的get变量