2011-02-23 136 views
1

我有一個MySQL表,它返回一個包含連續重複項(當按時間戳排序時)的值列表。MySQL:刪除連續的重複值

例如,查詢的時候,我只需要返回連續重複值:

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

這裏的數字被用於參考 - 中值實際上是字符串「綠色」,因此,對於上面情況下新的未使用名單將是:

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

是否有一種巧妙的方式來處理MySQL的這個問題?

使用Rails/ActiveRecord,這不應該有所作爲,但我可以做到這一點沒有問題manipulating an Array,只是想知道是否有一個更聰明的方式來處理這個問題。

+0

爲什麼格林在最終名單上兩次? – 2011-02-23 01:33:34

+0

預期結果故意或錯字是最後的'綠色'嗎? – 2011-02-23 03:41:27

+0

我想刪除*連續*重複,而不僅僅是重複。所以7-Green是6-Green的副本,因此被丟棄。 3-綠色保持原樣。 – 2011-02-23 03:47:40

回答

2

大廈艾克·沃克的回答,這可能是更復雜一點比它需要的是:

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

HAVING,您可以使用計算列。設置@last意味着它不會記住您最後一次查詢的值,這可能會給您帶來奇怪的結果。

3

解決此類問題的一種方法是對用戶變量使用子查詢。您可以使用用戶變量跟蹤上一行中的顏色值,然後在外部查詢的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 
0

如果很容易選擇不同的行。實際上刪除而不是您選擇的不同行有一點點工作。刪除語法比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