Mysql 更新组中最早的行
我正在尝试为MySQL构造一个SQL语句,它将更新组中的一行。根据下面的记录,我需要更新IsPrimary标志,以便将每个用户的最早记录设置为1Mysql 更新组中最早的行,mysql,sql,Mysql,Sql,我正在尝试为MySQL构造一个SQL语句,它将更新组中的一行。根据下面的记录,我需要更新IsPrimary标志,以便将每个用户的最早记录设置为1 ID | UserID | Inserted | IsPrimary ----------|-------------|-------------|---------- 000f83 | 79b8c3 | 2012-03-14 | 0 001401 | 79b8c3 | 2012-03-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
请尝试以下操作:
update t
set t.IsPrimary = 1
from myTable t
inner join myTable t2 on t.UserID = t2.UserID and t.Inserted<t2.Inserted
更新t
设置t.IsPrimary=1
来自MyT表
t.UserID=t2.UserID和t.Inserted上的内部联接myTable t2尝试以下操作:
update t
set t.IsPrimary = 1
from myTable t
inner join myTable t2 on t.UserID = t2.UserID and t.Inserted<t2.Inserted
更新t
设置t.IsPrimary=1
来自MyT表
t.UserID=t2.UserID和t.Inserted上的内部连接myTable t2
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
这是答案。请尝试一下:
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
以下是。一组中的几行是否可能在插入的中有相同的日期?否。我已将其缩写为问题的日期,但实际上字段也有时间。一组中的几行是否可能在插入的中有相同的日期?否。我已将其缩写为问题的日期,但在事实上,该字段也有一个时间。它将在组中的所有行中设置isprimary,但最后一行除外。我假设每个用户在样本中有两行。它将在组中的所有行中设置isprimary,但最后一行除外。我假设每个用户在样本中有两行。这看起来适用于只有两条记录的情况每个用户?我应该注意到,在大多数情况下可能会有两个以上。@sipwiz,请给我发送一个数据设置的小提琴,这样它就不会工作更多(它可以工作任何数量:)。你是对的。我确实有一些具有重复插入值的记录,但这是因为它们是测试数据,不会在生产中出现。看起来这适用于每个用户只有两条记录的情况?我应该注意到,在大多数情况下可能会有两个以上。@sipwiz,请给我发送一个数据设置的小提琴,这样它就不会工作更多(它可以工作任何数量:)。你是对的。我确实有一些带有重复插入值的记录,但这是因为它们是测试数据,不会在生产中出现。