MySQL UPDATE - MAX()GROUP BY

时间:2010-08-16 13:43:19

标签: sql mysql group-by

如何更改:

SELECT user.postcode, max(postcode.postcode) as postcode
FROM user
INNER JOIN postcode ON user.postcode LIKE CONCAT( postcode.postcode,  "%" )
GROUP BY user.postcode

进入类似于?

的UPDATE
UPDATE user 
INNER JOIN postcode ON user.postcode LIKE CONCAT(postcode.postcode, "%") 
SET user.lat = postcode.lat, user.lng = postcode.lng

我无法弄清楚如何考虑MAX()和GROUP BY

答案

以下是我的@ceteras代码版本。它很棒!

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.postcode;
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;

1 个答案:

答案 0 :(得分:2)

这是一次性工作吗? 如果是,请尝试:

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;