Is it possible to move a record from one table to another using a single SQL statement?

后端 未结 5 1749
我寻月下人不归
我寻月下人不归 2021-01-19 10:41

I need a query to move a record from one table to another without using multiple statements?

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-19 11:20

    If you really want to do this in a single SQL statement, one way to accomplish this would be to create an "after delete" trigger on the source table that inserts the row into the target table. This way you can move the row from the source table to the target table simply by deleting it from the source table. Of course this will only work if you want to insert into target table for every delete on the source table.

    DELIMITER $$
    
    DROP TRIGGER IF EXISTS TR_A_DEL_SOURCE_TABLE $$
    
    CREATE TRIGGER TR_A_DEL_SOURCE_TABLE AFTER DELETE ON SOURCE_TABLE FOR EACH ROW BEGIN
    
      INSERT IGNORE INTO TARGET_TABLE(id,val1,val2) VALUES(old.id,old.va1,old.val2);
    
    END $$
    
    DELIMITER ;
    

    So to move the row with id 42 from source table to target table:

    delete from source_table where id = 42;
    

提交回复
热议问题