2012-04-12 41 views
0

我正在嘗試爲MySQL更新組中的單個行構造一條SQL語句。以記錄下面我需要更新值isPrimary標誌,使每個用戶的最早記錄設置爲1更新組中最早的一行

ID  | UserID  | Inserted | IsPrimary 
----------|-------------|-------------|---------- 
000f83 | 79b8c3  | 2012-03-14 | 0 
001401 | 79b8c3  | 2012-03-15 | 0 
002e7d | 4652a2  | 2012-02-22 | 0 
003ca6 | 4652a2  | 2012-02-13 | 0 

所以上述記錄將最終成爲:

ID  | UserID  | Inserted | IsPrimary 
----------|-------------|-------------|---------- 
000f83 | 79b8c3  | 2012-03-14 | 1 
001401 | 79b8c3  | 2012-03-15 | 0 
002e7d | 4652a2  | 2012-02-22 | 0 
003ca6 | 4652a2  | 2012-02-13 | 1 
+0

組中的多行可能在'inserted'中有相同的日期嗎? – zerkms 2012-04-12 04:49:16

+0

不,我把它縮寫爲問題的日期,但實際上該領域也有時間。 – sipwiz 2012-04-12 05:01:11

回答

4

這給一個RY:

update t, (
    select t1.id anId from t t1 
    left join t t2 
    on t1.userId = t2.userId and t1.inserted > t2.inserted 
    where t2.inserted is null 
) s 
set IsPrimary = 1 
where t.id = anId 

這是fiddle

+0

它看起來像適用於每個用戶只有兩個記錄的情況?我應該注意到,在大多數情況下可以有2個以上。 – sipwiz 2012-04-12 05:02:08

+0

@sipwiz請給我一個設置數據的小提琴,這樣它就無法工作更多(它適用於任何數量:)。 – 2012-04-12 05:03:59

+1

@sipwiz:它應該適用於任何數量的記錄每組 – zerkms 2012-04-12 05:04:16

0

嘗試以下:

update t 
set t.IsPrimary = 1 
from myTable t 
inner join myTable t2 on t.UserID = t2.UserID and t.Inserted<t2.Inserted 
+0

它會在一個組中的所有行設置isprimary,除了最後一個 – zerkms 2012-04-12 04:51:43

+0

我假設每個用戶有兩行,如示例 – Vikram 2012-04-12 04:53:15