Replace contents of one table with another?

3

My case is as follows:

I have two tables TAB1 and TAB2 ; the two tables have the same structure: (id, name, nickname).

I would like to replace the contents of TAB1 with TAB2 . Everything in TAB2 must be deleted and replaced with TAB1 content.

I would also like to do this process only on a request to the database. How can I do this?

    
asked by anonymous 02.11.2016 / 10:44

2 answers

3
truncate table tab2;
insert into tab2 (SELECT * FROM tab1);
    
02.11.2016 / 10:54
3

It is not clear whether you want to know only the SQL commands or if you want to create the connection with a PHP script.

So, in a generic way,

First delete existing data:

DELETE FROM TAB2;

Then execute INSERT INTO TAB2 (SELECT * FROM TAB1);

You can do this by using a MySQL front-end like PHPMyAdmin.


*illustrativeimage

YoucannotdoyourqueriesatthesametimebecauseMySQLpreventsmultiplequeriesbydefault.Itispossibletochangethispatternbutitimpliessecurityissues.

It'simportanttonotethatifyoujustwanttoreplacethedatainonetablewiththedatainanothertable,youcouldonlyapplyREPLACEINTO,withoutusingtruncateordelete.

REPLACEINTOTAB2(SELECT*FROMTAB1)

That'senough.

Butforaspecificcasewhereyouwanttoclear"traces" from the TAB2 table that do not exist in TAB1 , it's best to delete everything before proceeding with INSERT .     

02.11.2016 / 11:52