一、查询重复数据
——–根据多个字段查询重复数据
SELECT
*
FROM
table_name a
WHERE
(a.字段1, a.字段2) IN (
SELECT
字段1,
字段2
FROM
table_name
GROUP BY
字段1,
字段2
HAVING
count(*) > 1
)
二、根据多个字段删除重复数据,只保留一条数据
注意:这种写法 必须保证有一个主键 如id,删除多余数据是 ,是根据id,保留最小或者最大的一条数据
DELETE
FROM
table_name
WHERE
(字段1, 字段2) IN (
SELECT
t.字段1,
t.字段2
FROM
(
SELECT
字段1,
字段2
FROM
table_name
GROUP BY
字段1,
字段2
HAVING
count(1) > 1
) t
)
AND id NOT IN (
SELECT
dt.id
FROM
(
SELECT
min(id) AS id
FROM
table_name
GROUP BY
字段1,
字段2
HAVING
count(1) > 1
) dt
)
三、没有主键时删除重复数据
###字段1,字段2,字段3,字段4,字段5,字段6 是表中所有字段
create table new_table_temp
select DISTINCT 字段1,字段2,字段3,字段4,字段5,字段6 from table_name
delete from table_name
insert into table_name
select * from new_table_temp
DROP TABLE new_table_temp