MySQL UPDATE - MAX() GROUP BY
How do I change:
SELECT user.postcode, max(postcode.postcode) as postcode
FROM user
INNER JOIN postcode ON user.postcode LIKE CONCAT( postcode.postcode, "%" )
GROUP BY user.postcode
into an UPDATE similar to?
UPDATE user
INNER JOIN postcode ON user.postcode LIKE CONCAT(postcode.postcode, "%")
SET user.lat = postcode.lat, user.lng = postcode.lng
I cannot work out how to factor in the MAX() and GROUP BY
Answer
Below is my version of @ceteras code. It works great!
DROP TABLE IF EXISTS tmp;
CREATE TABLE tmp AS
SELECT user.user_id, max(postcode.postcode) AS postcode, postcode.lat, postcode.lng
FROM user
INNER JOIN postcode ON user.postcode LIKE CONCAT( postcode.postcode, "%" )
GROUP BY user.postco开发者_C百科de;
ALTER TABLE tmp ADD PRIMARY KEY(user_id);
UPDATE user
INNER JOIN tmp ON user.user_id = tmp.user_id
SET user.lat1 = tmp.lat, user.lng1 = tmp.lng;
DROP TABLE tmp;
Is this a one-time job? If yes, try this:
drop table if exists tmp;
create table tmp as
SELECT user.postcode, max(postcode.postcode) as post_code
FROM user
INNER JOIN postcode ON user.postcode LIKE CONCAT( postcode.postcode, "%" )
GROUP BY user.postcode;
alter table tmp add unique key(postcode, post_code), add key (post_code, postcode);
UPDATE user
INNER JOIN tmp ON user.postcode = tmp.postcode
inner join postcode p on p.postcode = tmp.post_code
SET user.lat = p.lat, user.lng = p.lng;
drop table tmp;
精彩评论