There are two options
INSERT INTO newtable
SELECT * FROM oldtable
ORDER BY tmstamp_value
ON DUPLICATE KEY UPDATE email=VALUES(email), address=VALUES(address) ... ;
REPLACE INTO newtable
SELECT * FROM oldtable
ORDER BY tmstamp_value;
It mechanically performs a DELETE and an INSERT.
CAVEAT
Notice I applied the ORDER BY against the old table. This should help get the latest data for a give LastName, FirstName.
You should also add a UNIQUE INDEX on the new table as follows:
ALTER TABLE newtable ADD UNIQUE INDEX name_ndx (lastname,firstname);
UPDATE 2013-04-08 17:13 EDT
If you are doing updates, there are two ways to do this:
1. UPDATE JOIN
UPDATE
(SELECT lastname,firstname,phone,email
FROM oldtable ORDER BY lastname,firstname) A
LEFT JOIN newtable B USING (lastname,firstname)
SET B.phone=A.phone,B.email=A.email;
2. UPDATE JOIN with GROUP BY
UPDATE
(
SELECT BB.id,BB.phone,BB.email FROM
(SELECT lastname,firstname,MAX(id) id FROM oldtable GROUP BY lastname,firstname) AA
INNER JOIN oldtable BB USING (lastname,firstname)
) A INNER JOIN newtable B USING (id)
SET B.phone=A.phone,B.email=A.email;
Give it a Try !!!
Both options will take full advantage of the UNIQUE index on name.
This works - I had the JOIN wrong
UPDATE `events`
INNER JOIN `plays_in_events` ON (`plays_in_events`.`EventID` = `events`.`EventID`)
INNER JOIN `plays` ON (`plays_in_events`.`PlayID` = `plays`.`PlayID`)
SET events.Name = plays.Play
WHERE
events.Name IS NULL and plays_in_events.PlayID = 1
and the earlier comments were quite right, but it took me a while to 'get it' - thanks for your help. I had just copied the JOIN lines from the working SELECT query, but when I looked again, I could finally see what the commentators meant about events
appearing twice, and plays_in_events
not appearing properly in the JOINs.
Best Answer
LIMIT
is not allowed when theUPDATE
has joins. You can however move the join and theLIMIT
inside a subquery and then join back to the table to be updated using the primary or a unique key. This is allowed:It's also good to use
ORDER BY
withLIMIT
. Otherwise an arbitrary row will be selected.If you want to update both tables (one row from each one), then you just need to join the derived table to the second table, too:
Test at rextester.com