MySQL的:去除连续重复值 [英] MySQL: remove consecutive duplicate values
问题描述
我有一个MySQL表返回值的列表,其中包含的连续重复(当时间戳排序)。
I have a MySQL table that returns a list of values that contains consecutive duplicates (when ordered by a timestamp).
例如,查询的时候,我只需要返回连续重复的值:
For example, when querying, I need to only return the consecutively duplicated values:
[1, "Yellow"]
[2, "Yellow"]
[3, "Green"]
[5, "Black"]
[6, "Green"]
[7, "Green"]
这里的数字被用于参考 - 的值实际上字符串绿,因此对于上述情形,新unduped列表将是:
The numbers here are being used for reference - the value is actually the string "Green", so for the above case the new unduped list would be:
[1, "Yellow"]
[3, "Green"]
[5, "Black"]
[6, "Green"]
有没有处理这个问题,MySQL的一个聪明的办法?
Is there a smart way of handling this problem with MySQL?
使用Rails / ActiveRecord的,倒不是说应该有所作为,但我可以做到这一点没有任何问题,由<一个href="http://stackoverflow.com/questions/4576652/how-do-you-merge-consecutive-repeating-elements-in-an-array">manipulating阵列,只是不知道是否有处理这是一个更聪明的方式。
Using Rails/ActiveRecord, not that that should make a difference, but I can do this no problems by manipulating an Array, just wondering if there is a smarter way of handling this.
推荐答案
大厦艾克·沃克的回答,这可能是一个复杂一点比它需要的:
Building on Ike Walker's answer, which is possibly a bit more complex than it needs to be:
set @last='';
select id,@last as last_color,@last:=color as this_color
from your_table
having this_color != last_color;
HAVING
,您可以使用计算列。设置 @Last
意味着它不会从你跑一次查询,这可能会给你奇怪的结果还记得的价值。
HAVING
lets you use the computed columns. Setting @last
means it won't remember the value from the last query you ran, which might give you strange results.
这篇关于MySQL的:去除连续重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!