MySQL 中 DELETE 語句中可以使用別名麼?

DAYTOY-105發表於2024-04-15

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

相關文章