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.
You can insert the result of a SELECT using INSERT ... SELECT syntax. To get rows from one table that do not have corresponding rows in another you can use the A not in B LEFT JOIN MySQL idiom or a similar one with NOT EXIST subquery (though the latter is less efficient).
Please give your table details for more specific query.
Best Answer
You'll need to do it in several steps:
Add the column to the store (I'm not sure what the type is, maybe it's something else):
Populate it, based on the most prevalent location of the employees. I'm not entirely familiar with MySQL syntax but the query should look something like this:
The subquery (
locations_by_storeid
) lists all locations for employees on a certain storeid, and we take only the most frequent one (the one with row number 1) as per your requirement 2.Now we can remove the location from the employee: