我想根据时间戳和用户ID更新几行 所以我的数据看起来像这样
| INT(11) | TIMESTAMP | VARCHAR(50) |
| user id | timestamp | like id |
| 1 | 10/20/2014 10:30 | |
| 1 | 10/20/2014 9:45 | |
| 1 | 10/20/2014 22:30 | |
| 2 | 10/20/2014 9:45 | |
| 3 | 10/20/2014 10:30 | |
| 3 | 10/20/2014 9:45 | |
我想像这样更新具有相同用户ID和时间戳的行, 如果在具有相同用户ID的任何其他行中的一小时(同一天)内有另一个条目,则timestamp匹配。
| user id | timestamp | like id |
| 1 | 10/20/2014 10:30 | ASDF-1 |
| 1 | 10/20/2014 9:45 | ASDF-1 |
| 1 | 10/20/2014 11:30 | ASDF-1 |
| 1 | 10/20/2014 21:45 | ADGG-2 |
| 1 | 10/20/2014 22:30 | ADGG-2 |
| 2 | 10/20/2014 9:45 | GFDQ-3 |
| 3 | 10/20/2014 10:30 | QWER-4 |
| 3 | 10/20/2014 9:45 | QWER-4 |
这可以在MYSQL更新语句中执行吗?我还没有想到办法解决这个问题。
编辑:我还想为每个分组的like_ids生成一个随机的50char字符串
答案 0 :(得分:1)
这是一个返回所需内容的SQL查询:
select t.userid, t.timestamp,
(@rn := if(@u = userid and @ts <= timestamp + interval 1 hour,
if(@ts := timestamp, @rn, @rn),
if(@u := userid, if(@ts := timestamp, @rn + 1, @rn + 1), @rn + 1)
)
) as likeid
from table t cross join
(select @rn := 0, @u := 0, @ts := 0) vars
order by userid, timestamp;
嵌套if
的所有奇怪语法都是将变量的赋值放在一个语句中。
然后您可以将其用于更新:
update t join
(select t.userid, t.timestamp,
(@rn := if(@u = userid and @ts <= timestamp + interval 1 hour,
if(@ts := timestamp, @rn, @rn),
if(@u := userid, if(@ts := timestamp, @rn + 1, @rn + 1), @rn + 1)
)
) as likeid
from table t cross join
(select @rn := 0, @u := 0, @ts := 0) vars
order by userid, timestamp
) tnew
on t.userid = tnew.userid and t.timestamp = tnew.timestamp
set t.likeid = tnew.likeid;