mysql会根据特定的列删除除id最高的列以外的类似行

jjjwad0x  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(265)

我的表在特定列中有重复的行值。我要删除这些行并保留具有最新id的行。我要检查和比较的列包括:

sub_id, spec_id, ex_time

所以,这张table

+----+--------+---------+---------+-------+
| id | sub_id | spec_id | ex_time | count |
+----+--------+---------+---------+-------+
|  1 |    100 |     444 | 09:29   |     2 |
|  2 |    101 |     555 | 10:01   |    10 |
|  3 |    100 |     444 | 09:29   |    23 |
|  4 |    200 |     321 | 05:15   |     5 |
|  5 |    100 |     444 | 09:29   |     8 |
|  6 |    101 |     555 | 10:01   |     1 |
+----+--------+---------+---------+-------+

我想得到这个结果

+----+--------+---------+---------+-------+
| id | sub_id | spec_id | ex_time | count |
+----+--------+---------+---------+-------+
|  5 |    100 |     444 | 09:29   |     8 |
|  6 |    101 |     555 | 10:01   |     1 |
+----+--------+---------+---------+-------+

根据这个问题,我能够构建这个查询来从多个列中选择所有重复的行

select  t.*
from mytable t join
     (select id, sub_id, spec_id, ex_time, count(*) as NumDuplicates
      from mytable
      group by sub_id, spec_id, ex_time
      having NumDuplicates > 1
     ) tsum
     on t.sub_id = tsum.sub_id and t.spec_id = tsum.spec_id and t.ex_time = tsum.ex_time

但是现在我不知道如何用delete查询 Package 这个select来删除除id最高的行以外的行

owfi6suc

owfi6suc1#

您可以修改您的子选择查询,以获得 id 对于每个复制组合。
现在,在连接到主表时,只需输入一个条件 id 值将不等于最大值 id 价值观。
你现在可以了 Delete 从这个结果集中。
请尝试以下操作:

DELETE t 
FROM mytable AS t 
JOIN 
    (SELECT MAX(id) as max_id, 
            sub_id, 
            spec_id, 
            ex_time, 
            COUNT(*) as NumDuplicates
     FROM mytable
     GROUP BY sub_id, spec_id, ex_time
     HAVING NumDuplicates > 1
    ) AS tsum
     ON t.sub_id = tsum.sub_id AND 
        t.spec_id = tsum.spec_id AND 
        t.ex_time = tsum.ex_time AND 
        t.id <> tsum.max_id

相关问题