从 mysql table 结果中删除重复行

Remove duplicate rows from mysql table result

我有一个 table 命名的寄售,其中有一些重复的行与第 "service" 列相对应,其中 service='CLRC'.

select * from consignment where service='CLRC'

当我 select 行时,我总共有 2023 行,其中包括重复项。

我写了下面的查询来删除行,但我想先 select 它们以确保删除正确的记录。

当 select 运行时 returns 64431 条记录。对吗?

select t1.hawb FROM consignment t1
INNER JOIN consignment t2 
WHERE 
    t1.id < t2.id AND 
    t1.hawb = t2.hawb
    and t1.service='CLRC'

将匹配条件中除id列外的所有列作为主键:

delete t1 
  from consignment t1
  join consignment t2 
 where t1.id < t2.id 
   and t1.hawb = t2.hawb
   and t1.col1=t2.col1
   and t1.col2=t2.col2   
   ......
   and t1.service='CLRC';

Demo

您可以通过

查看重复的数量
select count(*) from
(
select distinct hawb, col1, col2, service --  (all columns except `id`)
  from consignment
) q 

在提交更改之前检查此数字是否等于已删除记录的数量。

如果您希望查询 return 重复项的数量,那么不,这是不正确的。
条件 t1.id < t2.id 会将 t1 的每个 idt2 中更大的所有 id 连接起来,从而导致更多行或更少行(在这种情况下只有 2 次重复)而且很少出现在预期的数量中。
参见 demo.
如果您想查看所有重复项:

select * from consignment t
where t.service = 'CLRC' 
and exists (
  select 1 from consignment
  where service = t.service and id <> t.id and hawb = t.hawb 
)  

参见demo
如果你想删除重复项并只保留每个 hawb 最大 id 的重复项,则:

delete from consignment
where service='CLRC'
and id not in (
  select id from (
    select max(id) id from consignment
    where service='CLRC' 
    group by hawb
  ) t  
);

参见demo