MySQL 中 delete 语句中的子查询限制

学习笔记 马富天 2019-10-11 14:48:50 21 3

【摘要】一条删除本表 id 最大的记录的 sql 语句,此时会先查询出本条的最大 id ,然后执行 delete ,而 mysql 中会对 select 子查询做限制,本文就此问题进行讲解说明。

场景一:

  1. delete from test where id in (select max(id) from test);
  2. [Err] 1093 - You can't specify target table 'test' for update in FROM clause
  3. delete from test where id = (select max(id) from test);
  4. [Err] 1093 - You can't specify target table 'test' for update in FROM clause

问题描述:如果子查询的 from 子句和更新(update)、删除(delete)对象操作的是同一张表,会出现上述报错。

解决办法:通过给 from 子句中的查询结果起别名。

正确语句:

  1. delete from test where id in (select max_id from (select max(id) as max_id from test) as t);

场景二:

  1. delete from test as t where t.id = 1;
  2. [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as t where t.id = 1' at line 1

问题描述:在 delete from table 这样的语句中 table 不能使别名。

解决办法:去掉 delete 语句中的别名。

正确语句:

  1. delete from test where id = 1;

小 tip (提示):

mysql 的别名可以大致分为 4 种:

字段别名、表别名、函数的结果别名(min()、max())、查询出来的结果起别名;

别名的写法是:要起别名的对象 as 别名(当然也可以去掉 as,不过推荐尽量使用别名)。

参考如下:

  1. # 字段别名:
  2. select name as '姓名' from table;
  3. # 表别名:
  4. select name from table as t where t.id = 1;
  5. # 函数结果别名:
  6. select max(id) as max_id from table;
  7. # 查询的结果别名:
  8. select t.name from (select id,name from table) as t;

版权归 马富天个人博客 所有

本文标题:《MySQL 中 delete 语句中的子查询限制》

本文链接地址:http://www.mafutian.com/430.html

转载请务必注明出处,小生将不胜感激,谢谢! 喜欢本文或觉得本文对您有帮助,请分享给您的朋友 ^_^

0

0

上一篇《 细说 python 切片 》 下一篇《 判断两张图片的内容是否一致【Python 两种方法】 》

所有评论

  1. 首页
  2. 上一页
  3. 1
  4. 下一页
  5. 尾页
  6. 第1页
  7. 每页12条
  8. 共1页
  9. 共3条
评论审核未开启
表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情 表情
验证码

TOP10

  • 浏览最多
  • 评论最多