2013-03-24 56 views
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; 

誰能請創建存儲過程或執行該單號查詢,謝謝

回答

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()(指到期日應小於今天的日期),這反映在查詢中。

+0

@Abeer拉扎它有幫助嗎?你的問題需要更多幫助嗎? – peterm 2013-03-25 00:20:30

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