MySQL 去重留一

2019-08-20 09:50:09 阅读:3 编辑
select * from 5kcrm_crm_customer where telephone='18050056050';
select count(*) from 5kcrm_crm_customer;

select count(DISTINCT telephone) as dis_count from 5kcrm_crm_customer;
保留重复(最小ID)

DELETE 5kcrm_crm_customer
FROM
    5kcrm_crm_customer, 
    (
        SELECT
            min(customer_id) customer_id,
            telephone
        FROM
            5kcrm_crm_customer
        GROUP BY
            telephone
        HAVING
            count(*) > 1
    ) t2
WHERE
    5kcrm_crm_customer.telephone = t2.telephone 
AND 5kcrm_crm_customer.customer_id > t2.customer_id;
保留重复(最新更新)
DELETE 5kcrm_crm_customer
FROM
    5kcrm_crm_customer, 
    (
        SELECT
            max(update_time) update_time,
            telephone
        FROM
            5kcrm_crm_customer
        GROUP BY
            telephone
        HAVING
            count(*) > 1
    ) t2
WHERE
    5kcrm_crm_customer.telephone = t2.telephone 
AND 5kcrm_crm_customer.update_time < t2.update_time;