MySQL 中 DELETE 语句中可以使用别名么?

1 情境

delete 
from
  test1 t1 
where
  not exists ( select 1 from test2 t2 where t1.id = t2.id );

以上sql报错
ERROR 1064 (42000): 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 't1 where not exists (select 1 from test2 t2 where t1.id=t2.id)' at line 1

 2 分析

这就有点奇怪了,因为我在执行删除语句之前,执行过同样条件的 SELECT 语句,只是把其中的 select * 换成了 delete 而已,毕竟这个语法的报错一般来说原因很大可能是 关键字拼写错误 或者 存在中文符号。

排除了上面的原因后,再从语句本身的逻辑来排查,难道说 DELETE 语句不支持 not exists 这种写法?好像之前也没听说过这个限制。我们还是以语法错误这个原因为起点,去查查官方文档看下能不能找出答案。
MySql 5.7版本单表delete语法如下:

delete [low_priority] [quick] [ignore] from tbl_name
    [partition (partition_name [, partition_name] ...)]
    [where where_condition]
    [order by ...]
    [limit row_count]
-- 会发现并无表别名的使用

MySql 8.0版本单表delete语法如下:

delete [low_priority] [quick] [ignore] from tbl_name [[as] tbl_alias]
    [partition (partition_name [, partition_name] ...)]
    [where where_condition]
    [order by ...]
    [limit row_count]

MySql 5.7 和 8.0 多表删除格式:

delete [low_priority] [quick] [ignore]
    tbl_name[.*] [, tbl_name[.*]] ...
    from table_references
    [where where_condition]

delete [low_priority] [quick] [ignore]
    from tbl_name[.*] [, tbl_name[.*]] ...
    using table_references
    [where where_condition]

分析结果:经过上面语法对比的不同发现,5.7 的单表删除确实不支持别名的使用,但是多表删除却支持(table_references 里包含别名的使用)

并且在 8.0.16 开始,单表删除已经支持使用别名了。

For consistency with the SQL standard and other RDBMS, table aliases are now supported in single-table as well as multi-table DELETE statements. (Bug #27455809)

3 结论

  • MySQL 5.7 使用单表删除语句时,不能使用别名,多表删除可以使用别名;
  • MySQL 8.0.16 开始单表多表都可以使用别名。
  • 更多技术文章,请访问:https://opensource.actionsky.com/

4 关于SQLE

SQLE 是一款全方位的 SQL 质量管理平台,覆盖开发至生产环境的 SQL 审核和管理。支持主流的开源、商业、国产数据库,为开发和运维提供流程自动化能力,提升上线效率,提高数据质量。

SQLE获取

类型 地址
版本库 https://github.com/actiontech/sqle
文档 https://actiontech.github.io/sqle-docs/
发布信息 https://github.com/actiontech/sqle/releases
数据审核插件开发文档 https://actiontech.github.io/sqle-docs/docs/dev-manual/plugins/howtouse

原文链接:https://blog.csdn.net/ActionTech/article/details/134555384

posted @ 2024-04-15 19:49  DAYTOY-105  阅读(18)  评论(0编辑  收藏  举报