0

I am trying to update one table from another in MYSQL, i did:

INSERT INTO new_table (id, last_name, first_name, etc) 
SELECT (id, last_name, first_name, etc) FROM uploaded_tmp
ON DUPLICATE KEY UPDATE

How do I instruct to update the values with the newer values?

Dean
  • 7,814
  • 8
  • 30
  • 31
  • You use `UPDATE` for updating, and `INSERT` for inserting – zerkms Nov 03 '14 at 10:18
  • or better "UPSERT", http://stackoverflow.com/questions/6107752/how-to-perform-an-upsert-so-that-i-can-use-both-new-and-old-values-in-update-par – matcheek Nov 03 '14 at 10:18

3 Answers3

1

There is a nice feature called REPLACE

REPLACE INTO new_table (id, last_name, first_name, etc) 
SELECT (id, last_name, first_name, etc) FROM uploaded_tmp

It behaves just like INSERT, but if duplicate key happens (either PRIMARY or UNIQUE), the old record will be deleted and replaced with new values.

Interested? Read more on http://dev.mysql.com/doc/refman/5.7/en/replace.html

David162795
  • 1,846
  • 3
  • 15
  • 20
  • That's wrong. It is ALWAYS an insert. The old dataset will be deleted and a new one inserted. So if you use `AUTO_INCREMENT` on your `PRIMARY`, there will be a new incremented ID. – BreyndotEchse Nov 03 '14 at 16:40
  • As long as even the primary key is being replaced, it will be the same. If the primary key is not included within replacing data, yes, it will get new index, I should update my answer. – David162795 Nov 03 '14 at 16:47
1

you are missing an update statement here.complete it with setting of some data

use :

INSERT INTO table(value)
SELECT id, uid
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE ut=uy,yt=iu.....

reference :Mysql site

Divya
  • 1,469
  • 1
  • 13
  • 25
1
  1. Are the IDs of new_table and uploaded_tmp the same? If not, remove them from the INSERT statement
  2. Do you need the ID to be the same after the update? If not see the answer of David162795.
  3. If you don't want your PRIMARY ID to change you have to use INSERT INTO ... ON DUPLICATE KEY UPDATE. But then we must know your UNIQUE indices

In this example there is a PRIMARY key (ID) and a UNIQUE index (last_name, first_name)

INSERT INTO new_table (
    last_name,
    first_name,
    val1,
    val2,
    ...
) 
SELECT
    last_name,
    first_name,
    val1,
    val2,
FROM uploaded_tmp
ON DUPLICATE KEY UPDATE
    val1 = VALUES(val1),
    val2 = VALUES(val2)
BreyndotEchse
  • 2,192
  • 14
  • 20