mysql - 从 mysql 表结果中删除重复行

标签 mysql sql sql-delete

我有一个名为 consignment 的表,其中针对“service”列有一些重复的行,其中 service='CLRC'。

select * from consignment where service='CLRC'

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

我编写了以下查询来删除行,但我想首先选择它们以确保其删除正确的记录。

当 select 运行时,它返回 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'

最佳答案

如果您希望查询返回重复项的数量,那么不,这是不正确的。
病情t1.id < t2.id将加入每个 idt1与所有id来自 t2较大会导致更多行或更少行(在只有 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 .
如果您想删除重复项并仅保留最大 id 的一个对于每个 hawb那么:

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 .

关于mysql - 从 mysql 表结果中删除重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120986/

相关文章:

mysql - LEFT 连接时 SQL DELETE 太长

php - 如何使用cakephp在mysql中插入多个选择框的值

mysql - Laravel 当足够n条记录时如何批量插入数据库?

sql - 使用 Groovy 批处理异构 SQL 准备语句?

mysql - 如何从现有余额中获取新的运行余额?

php - 如果未找到多个硬件,请从列表中删除所有值

hibernate - JPA2 多对多关系上的级联删除

mysql - MySQL 查询将内容从一个表插入到另一个表的逻辑问题

c# - MySql.Data.MySqlClient.MySqlException : “The host localhost does not support SSL connections.”

Mysql 获取最新的item数量