2012-04-12 67 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