MySql表自修改报错:You can‘t specify target table ‘student‘ for update in FROM clause

文章目录

一、发现问题

在一次准备处理历史数据sql时,出现这么一个问题:You can't specify target table '表名' for update in FROM clause,大致的意思就是:不能在同一张表中先select再update。

在此进行一下复盘沉淀,使用测试sql复现当时的场景(mysql是8版本),准备测试数据:

sql 复制代码
CREATE TABLE `student` (
  `id` int NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

INSERT INTO `athena_opencourse`.`student`(`id`, `name`, `address`) VALUES (1, '张三', '北京');
INSERT INTO `athena_opencourse`.`student`(`id`, `name`, `address`) VALUES (2, '李四', '上海');

二、场景1:在where条件中查询了修改表的数据

sql 复制代码
update student set address = '杭州'
where id in (select id from student where name = '张三');

delete from  student
where id in (select id from student where name = '张三');

此时会提示:1093 - You can't specify target table 'student' for update in FROM clause

解决方式:在where子句中再加一层,使其成为临时表:

sql 复制代码
update student set address = '杭州'
where id in (select tmp.id from (select id from student where name = '张三') tmp);

三、场景2:在set语句中查询了修改表的数据

sql 复制代码
update student set address = (select address from student where name = '李四')
where name = '张三';

此时,一样的报错:> 1093 - You can't specify target table 'student' for update in FROM clause

解决方式同上,查询时再加一层,使其成为临时表:

sql 复制代码
update student set address = (select tmp.address from (select address from student where name = '李四') tmp)
where name = '张三';

或者使用update join的方案:

sql 复制代码
update student s1 ,student s2 
set s1.address = s2.address
where s1.name = '张三' and s2.name = '李四';

惊呆了有木有!使用update join语法,可以很轻松的实现跨表的数据修改。

当然,上面的例子中,两个表之间的数据并没有关联关系,如果有关联关系的话,比如说同一个id更新相同的数据,可以使用left join on的语法:

sql 复制代码
update student s1 
left join student s2 on s1.id = s2.id
set s1.address = s2.name;
相关推荐
apihz13 分钟前
域名WHOIS信息查询免费API使用指南
android·开发语言·数据库·网络协议·tcp/ip
gwcgwcjava19 分钟前
[时序数据库-iotdb]时序数据库iotdb的安装部署
数据库·时序数据库·iotdb
SHUIPING_YANG34 分钟前
根据用户id自动切换表查询
java·服务器·数据库
爱吃烤鸡翅的酸菜鱼1 小时前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
超奇电子1 小时前
阿里云OSS预签名URL上传与临时凭证上传的技术对比分析
数据库·阿里云·云计算
modelmd1 小时前
mysql not in 查询引发的bug问题记录
sql·mysql
神仙别闹1 小时前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
m0_653031361 小时前
PostgreSQL技术大讲堂 - 第97讲:PG数据库编码和区域(locale)答疑解惑
数据库·postgresql
会编程的林俊杰2 小时前
MySQL中的锁有哪些
数据库·mysql
cts6182 小时前
Milvus分布式数据库工作职责
数据库·分布式·milvus