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


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
); 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM