MySQL:删除连续的重复值

我有一个MySQL表,返回包含连续重复项的值列表(按时间戳排序)。

例如,在查询时,我只需要返回连续重复的值:

[1, "Yellow"] [2, "Yellow"] [3, "Green"] [5, "Black"] [6, "Green"] [7, "Green"] 

这里的数字用于参考 – 该值实际上是字符串“Green”,因此对于上述情况,新的未列出的列表将是:

 [1, "Yellow"] [3, "Green"] [5, "Black"] [6, "Green"] 

有没有一种聪明的方法来处理MySQL的这个问题?

使用Rails / ActiveRecord,而不是那应该有所作为,但我可以通过操作数组来做到这一点,只是想知道是否有更聪明的方法来处理它。

以Ike Walker的答案为基础,这可能比它需要的更复杂:

 set @last=''; select id,@last as last_color,@last:=color as this_color from your_table having this_color != last_color; 

HAVING允许您使用计算列。 设置@last意味着它不会记住您运行的上一个查询的值,这可能会给您带来奇怪的结果。

解决此类问题的一种方法是使用带有用户变量的子查询。 您可以使用用户变量跟踪上一行的颜色值,然后使用外部查询的where子句中的用户变量来过滤返回的行。

尝试这样的事情:

 select id,this_color as color from ( select id,@last as last_color,@last:=color as this_color from your_table order by id ) as sub where this_color != last_color 

如果非常简单,请选择不同的行。 实际上删除不是您选择的不同行还有一些工作要做。 删除中的语法比select更加挑剔。 您必须正式声明另一个表并加入反对(它不会让您在where子句中创建相关子查询。)

在子查询中选择要删除的ID,然后在delete语句中对其进行连接:

 delete from test using test, ( -- the rows i do not want select id from test where id not in -- select the rows i do want (will use the minimum id instead of being arbitrary) (select min(id) as id from test group by color) ) as temp where test.id = temp.id ; 

这些是子查询选择的行:

 id color 2 yellow 6 green 7 green 

删除后的最后一行:

 id color 1 yellow 3 green 5 black