Mysql 相同字段的多条记录去重只保留日期为最新的一条

1、sql

SELECT
 b.*SELECT
 b.*
FROM
   customer_phone  b
WHERE b.id =
  (SELECT
    MAX(a.id)
  FROM
    customer_phone a
  WHERE a.customerId = b.customerId);

FROM
   customer_phone  b
WHERE b.createTime =
  (SELECT
    MAX(a.createTime)
  FROM
    customer_phone a
  WHERE a.customerId = b.customerId);

2、如果主键是自增的可以考虑使用最大id代表最新时间

SELECT
  c.*
FROM
  customer_info c,
  customer_phone b
WHERE b.id =
  (SELECT
    MAX(a.id)
  FROM
    customer_phone a
  WHERE a.customerId = b.customerId)
  AND c.isRealName = 1
  AND c.idCardType = 1

你可能感兴趣的:(数据库使用与维护,Mysql)