mysql 的delete from where 子查询的一些限制

1.使用mysql进行delete from操作时,若子查询的 FROM 字句和更新/删除对象使用同一张表,会出现错误。
mysql> DELETE FROM ‘tab’ where id in (select min(id) from tag GROUP BY field1,field2 HAVING COUNT(id)>1);
error: You can’t specify target table ‘tab’ for update in FROM clause.(不能为FROM子句中的更新指定目标表’tab’)

针对“同一张表”这个限制,多数情况下都可以通过多加一层select 别名表来变通解决,像这样

DELETE FROM 'tab' where id in
(
    select id from 
    (
        select max(id) from 'tab' GROUP BY field1,field2 HAVING COUNT(id)>1
    ) ids
);

2.delete from table… 这其中table不能使用别名

  • mysql> delete from table a where a.id in (1,2);(语法错误)
  • mysql> select a.* from table a where a.id in (1,2);(执行成功)
    原文作者:啊哈
    原文地址: https://segmentfault.com/a/1190000018181183
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞