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