The searlea answer is nice, but as stated in the comments, you lose foreign keys during the battle. this solution is similar: truncate is executed within a second, but you save foreign keys.
The trick is that we disabled / activated the FK checks.
SET FOREIGN_KEY_CHECKS=0; CREATE TABLE NewFoo LIKE Foo; insert into NewFoo SELECT * from Foo where What_You_Want_To_Keep truncate table Foo; insert into Foo SELECT * from NewFoo; SET FOREIGN_KEY_CHECKS=1;
Extended answer - Delete all but some lines
My problem: due to a crazy script, there were 7,000,000 unwanted rows in my table. I needed to delete 99% of the data in this table, so I needed to copy what I want to save in the tmp table before deleting.
These Foo rows that I need to save depend on other tables that have foreign keys and indexes.
something like that:
insert into NewFoo SELECT * from Foo where ID in ( SELECT distinct FooID from TableA union SELECT distinct FooID from TableB union SELECT distinct FooID from TableC )
but this request was always turned off after 1 hour. Therefore, I had to do it as follows:
CREATE TEMPORARY TABLE tmpFooIDS ENGINE=MEMORY AS (SELECT distinct FooID from TableA); insert into tmpFooIDS SELECT distinct FooID from TableB insert into tmpFooIDS SELECT distinct FooID from TableC insert into NewFoo SELECT * from Foo where ID in (select ID from tmpFooIDS);
Theory
I, because the indexes are configured correctly, I think that both methods of filling NewFoo should have been the same, but it was not practical.
That is why in some cases you can do the following:
SET FOREIGN_KEY_CHECKS=0; CREATE TABLE NewFoo LIKE Foo; -- Alternative way of keeping some data. CREATE TEMPORARY TABLE tmpFooIDS ENGINE=MEMORY AS (SELECT * from Foo where What_You_Want_To_Keep); insert into tmpFooIDS SELECT ID from Foo left join Bar where OtherStuff_You_Want_To_Keep_Using_Bar insert into NewFoo SELECT * from Foo where ID in (select ID from tmpFooIDS); truncate table Foo; insert into Foo SELECT * from NewFoo; SET FOREIGN_KEY_CHECKS=1;
Xavier Mar 02 2018-02-17T00: 00Z
source share