問題
執行如下sql要刪除一些錯誤數據
delete from user_tag where tagId in (
select ut.tagId from user_tag ut
left join tag t on ut.tagId = t.tagId
where t.tagId is null
)
結果
結果SQL錯誤,這是MySQL特有的一個現象
delete from user_tag where tagId in (
select ut.tagId from user_tag ut
left join tag t on ut.tagId = t.tagId
where t.tagId is null
)
> 1093 - You can't specify target table 'user_tag' for update in FROM clause
> 時間: 0.001s
解決方案
修改爲如下方式,delete 的
select count(1) from tag t ; -- 177
select count(1) from user_tag ; -- 647
delete from user_tag where tagId in (
select tagId from (select ut.tagId from user_tag ut
left join tag t on ut.tagId = t.tagId
where t.tagId is null ) tt
)
> Affected rows: 95
> 時間: 0.008s
結論
MySQL 不能在更新或刪除的子語句中直接使用本表,可通過再套一層的方式繞過。