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  
4

2 に答える 2

4

これを試してください:

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

これがフィドルです。

于 2012-04-12T04:53:10.443 に答える
0

以下を試してください:

update t
set t.IsPrimary = 1
from myTable t
inner join myTable t2 on t.UserID = t2.UserID and t.Inserted<t2.Inserted
于 2012-04-12T04:50:51.953 に答える