首页 > 数据库技术 > 详细

MySQL使用子查询作为delete或update的条件

时间:2020-06-28 20:23:16      阅读:73      评论:0      收藏:0      [点我收藏+]

update和delete的使用方式一样,下面以delete示例

1、如果delete(update)使用的表和子查询的表不是同一张表,直接使用子查询结果即可:

delete from table_1
    where id = (
        select id
        from table_2
        where create_date = 2020-06-28
      limit 1
);

2、如果是同一张表,像上面一样直接使用子查询结果会出错

delete from table_1
    where id = (
        select id
        from table_1
        where create_date = 2020-06-28
        limit 1
);

会报错:[Err] 1093 - You can‘t specify target table ‘trade_order‘ for update in FROM clause,意思是不能对同一张表同时使用select和删改语句,因此需要使用到临时表

delete from table_1
where id = (select id from 
         (select id
          from table_1
          where create_date = 2020-06-28
          limit 1
          ) a1
); 

就能成功执行了

ps: 如果需要给delete使用的表起个别名,则需要这样写

delete a2 from table_1 a2
where id = (select id from 
         (select id
          from table_1
          where create_date = 2020-06-28
          limit 1
          ) a1
); 

 

MySQL使用子查询作为delete或update的条件

原文:https://www.cnblogs.com/ayatsuji/p/13204465.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!