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;
相关推荐
格调UI成品5 分钟前
DCS+PLC协同优化:基于MQTT的分布式控制系统能效提升案例
数据库·云边协同
牵牛老人1 小时前
Qt C++ 复杂界面处理:巧用覆盖层突破复杂界面处理难题之一
数据库·c++·qt
a_blue_ice1 小时前
JAVA 面试 MySQL
java·mysql·面试
GBASE1 小时前
GBASE南大通用技术分享:构建最优数据平台,GBase 8s数据库安装准备(三)
数据库
言之。1 小时前
Django REST Framework 中 @action 装饰器详解
数据库·sqlite
十八旬3 小时前
苍穹外卖项目实战(day7-1)-缓存菜品和缓存套餐功能-记录实战教程、问题的解决方法以及完整代码
java·数据库·spring boot·redis·缓存·spring cache
Java水解4 小时前
【MySQL】数据库基础
后端·mysql
沃夫上校4 小时前
MySQL 中文拼音排序问题
java·mysql
要一起看日出4 小时前
MVCC-多版本并发控制
数据库·mysql·mvcc
Hx__4 小时前
MySQL InnoDB 的 MVCC 机制
数据库·mysql