I have two tables in my database, table1 and table2. They are identical. But sometimes I change the data in table1.
How do I copy the data from table1 and update table2 to look the same?
I tried REPLACE INTO table2 SELECT * FROM table1
but it works like INSERT and just make new rows instead of updating the existing ones.
For REPLACE INTO
to work as intended, the destination table must have a primary key defined, otherwise MySQL cannot determine whether a row already exists and always assumes a new row. As a result, for tables without a primary key, REPLACE INTO
acts exactly like INSERT INTO
.
Alternatively, you can use two queries, one UPDATE
and one INSERT
, with appropriate WHERE (NOT) EXISTS
clauses. The advantage of this is that it's portable ( REPLACE INTO
is a MySQL extension).
Another alternative is to run two commands...
truncate table table2;
insert into table2 select * from table1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.