0
select id as ids from challenges where expire_date > today

我需要循环她以获取多个 ID,例如(php 中的 foreach)

foreach (ids) 

    update challenges set status = 'expired' where id = ids

    update user_challenge set challenge_status = 'Expired' where challenge_status = 'Pending' and challenge_id = ids 
    update user_challenge set challenge_status = 'Failed' where challenge_status = 'Accepted' and challenge_id = ids 

end for each;

任何人都可以创建存储过程或单个查询来执行此操作,谢谢

4

2 回答 2

1

您在 MySql 中的单个更新查询可能如下所示

UPDATE user_challenge u INNER JOIN
       challenges c ON u.challenge_id = c.id
   SET c.status = 'Expired',
       u.challenge_status = CASE WHEN u.challenge_status = 'Pending' THEN 'Expired' 
                                 WHEN u.challenge_status = 'Accepted' THEN 'Failed' END
 WHERE c.expire_date < CURDATE()

这是SQLFiddle示例

我认为到期的条件应该是expire_date < CURDATE()(意味着到期日期应该小于今天的日期),这反映在查询中。

于 2013-03-24T19:09:18.607 回答
0

您可以声明一个游标,使用游标循环查询查询的结果

此语法适用于 T-SQL,但对于 MySQL 应该类似:

declare @id int
declare @cursor cursor;
set @cursor = cursor for select id as ids from challenges where expire_date > today
open @cursor
fetch next from @cursor into @id
while(@@FETCH_STATUS = 0)
begin
   update challenges set status = 'expired' where id = @id

    update user_challenge set challenge_status = 'Expired' where challenge_status = 'Pending' and challenge_id = @id
    update user_challenge set challenge_status = 'Failed' where challenge_status = 'Accepted' and challenge_id = @id 

  fetch next from @cursor into @id   
end
close @cursor
deallocate @cursor
于 2013-03-24T19:14:20.160 回答