删除MySQL中具有不同ID的连续重复值

删除MySQL中具有不同ID的连续重复值,mysql,duplicates,Mysql,Duplicates,我知道在mySQL中查找和删除重复值有很多相同的问题,但我的问题有点不同: 我有一个列为ID、Timestamp和price的表。脚本从另一个网页上抓取数据,并每10秒将其保存到数据库中。有时数据会以如下方式结束: | id | timestamp | price | |----|-----------|-------| | 1 | 12:13 | 100 | | 2 | 12:14 | 120 | | 3 | 12:15 | 100

我知道在mySQL中查找和删除重复值有很多相同的问题,但我的问题有点不同: 我有一个列为ID、Timestamp和price的表。脚本从另一个网页上抓取数据,并每10秒将其保存到数据库中。有时数据会以如下方式结束:

| id | timestamp | price |   
|----|-----------|-------|   
| 1  | 12:13     | 100   |   
| 2  | 12:14     | 120   |   
| 3  | 12:15     | 100   |   
| 4  | 12:16     | 100   |   
| 5  | 12:17     | 110   |   
如您所见,有3个重复的值,删除ID=4的price将缩小表,而不会破坏数据完整性。我需要删除连续的重复记录,除了第一个ID或时间戳最低的记录。 有没有足够的方法来做这件事?大约有一百万张唱片
我编辑了我的剪贴脚本,以便在添加之前检查重复的价格,但我需要收缩并维护我的旧数据。

我的查询基于@Tim Biegeleisen one

-- delete records
DELETE
FROM yourTable t1
-- where exists an older one with the same price
WHERE EXISTS (SELECT 1
              FROM yourTable t2
              WHERE t2.price = t1.price
                    AND t2.id < t1.id
-- but does not exists any between this and the older one
                    AND NOT EXISTS (SELECT 1
                                    FROM yourTable t3
                                    WHERE t1.price <> t3.price
                                          AND t3.id > t2.id
                                          AND t3 < t1.id));
它删除存在相同价格但不存在任何不同价格的旧记录的记录


如果id列不是数字和升序,则可以通过时间戳列进行检查。

我的查询基于@Tim Biegeleisen one

-- delete records
DELETE
FROM yourTable t1
-- where exists an older one with the same price
WHERE EXISTS (SELECT 1
              FROM yourTable t2
              WHERE t2.price = t1.price
                    AND t2.id < t1.id
-- but does not exists any between this and the older one
                    AND NOT EXISTS (SELECT 1
                                    FROM yourTable t3
                                    WHERE t1.price <> t3.price
                                          AND t3.id > t2.id
                                          AND t3 < t1.id));
它删除存在相同价格但不存在任何不同价格的旧记录的记录


如果id列不是数字和升序,则可以通过时间戳列进行检查。

我只是根据价格进行分组,并且每个组只筛选一条记录。显示最低id。希望下面的内容有所帮助

 select id,timestamp,price from yourTable group by price having count(price)>0;

我只是根据价格分组,每个组只过滤一条记录。显示最低的id。希望下面的帮助

 select id,timestamp,price from yourTable group by price having count(price)>0;

从MySQL 8.0开始,您可以通过以下方式使用窗口功能:

delete tbl.* from tbl
join (
    -- use lag(price) for get value from previous row
    select id, lag(price) over (order by id) price from tbl
) l 
-- join rows with same previous price witch will be deleted
on tbl.id = l.id and tbl.price = l.price;

从MySQL 8.0开始,您可以通过以下方式使用窗口功能:

delete tbl.* from tbl
join (
    -- use lag(price) for get value from previous row
    select id, lag(price) over (order by id) price from tbl
) l 
-- join rows with same previous price witch will be deleted
on tbl.id = l.id and tbl.price = l.price;

谢谢你的回答,但我执行起来很困难。它给了我错误1064。这个错误是由不好的评论丢失空格引起的。谢谢你的回答,但是我很难执行它。它给了我错误1064。错误是由于不好的评论丢失空格添加了一些解释添加了一些解释