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

后端 未结 5 1693
我寻月下人不归
我寻月下人不归 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:17

    There is no way to make it a single query, but if you HAVE to do it in a single query within an application you can create a Stored Procedure to do it for you.

    DELIMITER $$
    
    DROP PROCEDURE IF EXISTS `copydelete` $$
    CREATE PROCEDURE `copydelete` (id INT)
    BEGIN
    INSERT INTO New_Table SELECT * from Old_Table WHERE Old_Table.IdField=id;
    DELETE FROM Old_Table where IdField=id;
    END $$
    
    DELIMITER ;
    

    Then you're new query is just

    CALL copydelete(4);
    

    Which will delete WHERE IdField=4;

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-01-19 11:32

    Please note that the time delay between insert-select and delete can cause you to delete to much.

    For a safe route you could use an update field:

    update old_table set move_flag=1 where your_criteria
    insert into ... select from ... where move_flag = 1
    delete from old_table where move_flag=1
    

    Or use a transaction which locks the old_table so no data can be added between insert... select and delete.

    0 讨论(0)
  • 2021-01-19 11:38

    No, you cannot move records in one SQL statement. You have to use an INSERT followed by a DELETE statement. You should wrap these statements into a transaction, to make sure that the copy operation remains atomic.

    START TRANSACTION;
    
    INSERT INTO 
        new_table 
    SELECT 
        *
    FROM
        old_table
    WHERE
        some_field = 'your_criteria';
    
    DELETE FROM old_table WHERE some_field = 'your_criteria';
    
    COMMIT;
    
    0 讨论(0)
  • 2021-01-19 11:42

    No - you might be able to do the INSERT in one nested statement, but you still need to remove the record.

    0 讨论(0)
提交回复
热议问题