Home >Database >Mysql Tutorial >How to Efficiently Transfer and Delete SQL Rows Based on Matching Criteria?
Transferring Data: Moving Rows from One SQL Table to Another
Initial Issue:
Users aim to transfer data from one SQL table to another based on specific matching criteria. In this particular case, the query requires moving all rows from Table1 to Table2 that satisfy the conditions "username = 'X'" and "password = 'X'." Afterward, these rows should be deleted from Table1.
Technical Solution:
To efficiently execute this data migration, a two-step process can be employed within a single SQL transaction. This involves an initial insertion and a subsequent deletion:
BEGIN TRANSACTION; INSERT INTO Table2 (<columns>) SELECT <columns> FROM Table1 WHERE <condition>; DELETE FROM Table1 WHERE <condition>; COMMIT;
Additional Considerations:
For cases where new records matching the specified criteria might get added to Table1 between the insertion and deletion processes, a more elaborate query can be used:
BEGIN TRANSACTION; INSERT INTO Table2 (<columns>) SELECT <columns> FROM Table1 WHERE <condition> AND NOT EXISTS (SELECT 1 FROM Table2 WHERE <condition>); DELETE FROM Table1 WHERE <condition>; COMMIT;
This addition ensures that only the original matching rows from Table1 are transferred to Table2 and subsequently removed from Table1.
The above is the detailed content of How to Efficiently Transfer and Delete SQL Rows Based on Matching Criteria?. For more information, please follow other related articles on the PHP Chinese website!