当前位置: 首页 > news >正文

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

文章目录

  • 一、发现问题
  • 二、场景1:在where条件中查询了修改表的数据
  • 三、场景2:在set语句中查询了修改表的数据

一、发现问题

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

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

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条件中查询了修改表的数据

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子句中再加一层,使其成为临时表:

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

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

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

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

update student set address = (select tmp.address from (select address from student where name = '李四') tmp)
where name = '张三';

或者使用update join的方案:

update student s1 ,student s2 
set s1.address = s2.address
where s1.name = '张三' and s2.name = '李四';

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

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

update student s1 
left join student s2 on s1.id = s2.id
set s1.address = s2.name;

http://www.lryc.cn/news/218701.html

相关文章:

  • LeetCode 热题100——链表专题
  • 植物花粉深度学习图片数据集大合集
  • 面试算法48:序列化和反序列化二叉树
  • 【Python基础】Python编程入门自学笔记,基础大全,一篇到底!
  • windows自动登陆
  • 5G及其后的5G非地面网络:趋势和研究挑战-HARQ部分
  • 【WPF系列】- XAML语法规范
  • antv/g6之图布局及切换布局
  • Wordpress plugin removes ‘/category‘
  • 【大数据基础平台】星环TDH社区集群版本部署
  • 【Java】汉诺塔
  • Java实现对Html文本的处理
  • Vue项目创建与启动(2023超详细的图文教程)
  • EtherCAT主站读取从站EEPROM抓包分析
  • Elasticsearch 8.X 如何生成 TB 级的测试数据 ?
  • 汽车标定技术(四)--问题分析:多周期测量时上位机显示异常
  • Flink SQL时间属性和窗口介绍
  • Tomcat免安装版修改标题名称和进程
  • vim搜索、替换tab
  • 一文读懂ARM安全性架构和可信系统构建要素
  • Voice vlan、ICMP、单臂路由、mux-vlan
  • TCP IP 网络编程(七) 理解select和epoll的使用
  • Linux accept和FD_xxx的使用
  • 树结构及其算法-二叉运算树
  • vue的rules验证失效,部分可以部分又失效的原因
  • c#字符串转整数类型
  • 【LeetCode】118. 杨辉三角
  • 【Vue.js】Vue3全局配置Axios并解决跨域请求问题
  • 【车载开发系列】CRC循环冗余校验码原理
  • 数据库实验:SQL的数据更新