我有一个名为 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
将加入每个 id
的t1
与所有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/