Mysql DELETE 不能使用別名? 是我不會用!
阿新 • • 發佈:2022-01-17
今天碰到一個sql問題,就是在delete中加了別名,導致報錯了:"[Err] 1064 - You have an error in your SQL syntax; ..."
簡單說下過程,本來是一個簡單的delete語句:
delete from table1 where status=2;
後需要增加關聯條件,所以在後邊追加了where條件,為了關聯寫著方便為表添加了別名,變為:
就是這樣報錯了,提示語法錯誤,覺得挺納悶,將delete 換成 select * (通常為了省事,驗證sql的時候換成select),沒有問題,執行正確。
百度很多說“mysql delete 不能使用別名”的,去掉別名後果然正常:
delete from table1 where status=2 and EXISTS (select id from table2 where table2.fid=table1.id)
雖然問題解決了,但是更納悶了,delete不能用別名?!,當然不是,是我用錯了!
delete a from table1 a where a.status=2 and EXISTS (select b.id from table2 b where b.fid=a.id)
如上,delete使用別名的時候,要在delete和from間加上刪除表的別名,這樣才是正確的寫法。
DELETE的語法詳見(這是MySQL的要求,在oracle上沒有)