Mysql insert into on duplicate key

今天发现上周的一个sql写错了,调查后发现了一些duplicate 的一些用法。

SQL语句如下:

INSERT INTO weee_comm.`mailchimp_list_member` ( `user_id`, `email_address`, `first_name`, `last_name`, `area_code`, `country`, `state`, `city`, `zipcode`, `weekday`, `active_type`, `active_user`, `purchased`, `status` ) SELECT alluser.user_id, alluser.email 'email_address', alluser.first_name, alluser.last_name, alluser.delivery_area_code AS 'area_code', alluser.country, alluser.state, alluser.city, alluser.zip_code 'zipcode', alluser.week_day 'weekday', alluser.type AS 'active_type', alluser.active AS 'active_user', IFNULL(purchased.has_purchased, 'No') purchased, 'A' FROM (SELECT LOWER(u.email) 'email', uz.user_id, IFNULL( m.delivery_addr_firstname, u.alias ) 'first_name', IFNULL(m.delivery_addr_lastname, '') 'last_name', z.delivery_area_code, z.country, z.state, z.city, z.zipcode 'zip_code', z.weekday 'week_day', c.type, IF(c.id IS NULL, 'N', 'Y') 'active' FROM weee.user_zipcode uz JOIN weee.user u ON u.global_user_id = uz.user_id JOIN gb_zipcode_area z ON z.zipcode = uz.zipcode LEFT JOIN weee_job.user_classification c ON c.user_id = uz.user_id LEFT JOIN weee.member m ON m.user_id = uz.user_id WHERE LENGTH(u.email) > 0 AND u.email NOT LIKE '\_%' ORDER BY uz.user_id) alluser LEFT JOIN (SELECT o.rec_creator_id, 'YES' AS 'has_purchased' FROM gb_deal d JOIN gb_order o ON d.id = o.deal_id WHERE d.owner_id = 5044 AND d.end_time >= UNIX_TIMESTAMP( SUBDATE( CURDATE(), DATE_FORMAT(CURDATE(), '%w') ) ) AND d.end_time <= UNIX_TIMESTAMP( SUBDATE( CURDATE(), DATE_FORMAT(CURDATE(), '%w') -7 ) ) AND o.status != 'X' GROUP BY 1) purchased ON alluser.user_id = purchased.rec_creator_id ON DUPLICATE KEY UPDATE `status` = IF( `area_code` != VALUES (area_code) OR `zipcode` != VALUES (zipcode) OR `weekday` != VALUES (`weekday`) OR `active_type` != VALUES (active_type) OR `active_user` != VALUES (active_user) OR `purchased` != VALUES (purchased), 'U', NULL ), `area_code` = VALUES (area_code), `zipcode` = VALUES (zipcode), `weekday` = VALUES (`weekday`), `active_type` = VALUES (active_type), `active_user` = VALUES (active_user), `purchased` = VALUES (purchased) ;


感觉很复杂,后面status的更新与要更新的其他字段也有联系,本来status是最后一个字段,但是因为字段判断有联系,需要放到update的最前面, 然后就是ON DUPLICATE KEY UPDATE 里面values的使用。

中间还出现了

Column 'XXX' in field list is ambiguous

错误,又把alluser里面取出来的时候的一些字段重新别名了一下。



“在一切破旧褪色中,请你永远闪烁。”

你可能感兴趣的:(Mysql insert into on duplicate key)