Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Copy entire row from one to another and delete original

Tags:

mysql

Could someone please explain (or point in right direction) how I would move multiple rows from one table to another and remove the row from the original table based on a set criteria?

I understand

INSERT INTO table2 SELECT * FROM table1

to copy the data from one table to another but I need to then remove the original. The reason being it has been suggested to speed up the querying of the table I should move all redundant data (ended, expired, products older than 3 months) from the main table to another one.

A bit of background, I have a table that holds products, some products have expired but the products still need to be accessible. There are about 50,000 products that have expired and 2,000 which are active. There is a status column (int 1 = active, 2 = expired etc) to determine what to show on the front end.

I guess this post is 2 questions:

  1. Is there a better way to speed up the querying of the product table without removing expired items?
  2. If not, how to move rows from one table to another

Many many thanks!

like image 423
puks1978 Avatar asked Dec 27 '22 09:12

puks1978


2 Answers

INSERT INTO table2 (column_name1, column_name2) SELECT column_name1, column_name2 FROM table 1 WHERE (where clause here)

DELETE FROM table1 WHERE (where clause here)

Source for above: mysql move row between tables

like image 104
Keatinge Avatar answered Dec 28 '22 21:12

Keatinge


50,000 records in the table really isn't that many. If you're having performance issues, I'd look at your queries and your indexes to help speed up performance. And since those expired records still need to be accessed, then it could be more difficult having multiple tables to maintain.

However, to move data from one table to another as you've asked, you just need to run 2 different statements. Assuming you want to move inactive products:

INSERT INTO ProductsBackup SELECT * FROM Products WHERE Status <> 1
DELETE FROM Products WHERE WHERE Status <> 1

If you have Identities on your columns, you might be better off specifying the column names. But assuming the ProductId is the Identity, then be careful moving those to a different table as you probably don't want to lose that original id as it may point to other tables.

Good luck.

like image 32
sgeddes Avatar answered Dec 28 '22 23:12

sgeddes