select id as ids from challenges where expire_date > today
我需要循环她的多个id,如(foreach in php)
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;
任何人都可以创建存储过程或单个查询来执行此操作,谢谢
答案 0 :(得分: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()
(意味着到期日应该小于今天的日期),这反映在查询中。
答案 1 :(得分: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