Executing a stored procedure with cursor in PHP

大兔子大兔子 提交于 2019-12-02 08:48:06
Drew

Based on discussions in chat for 3 groupings, and this provided SQLFiddle for test data (not much data there).

Due to testing data with a sliding window of where now() is in relation to that data, the following variable was used to "freeze" now(). Simply to facilitate testing and verification of output.

So, ditch that ultimately and change the 4 references in the code that use it (note that Group 3 uses it twice).

The now() variable:

select @theNow:=now();
-- REM OUT the following line. It is used only for testing (as now will chg, your data won't)
select @theNow:='2016-06-23 14:00:00';

The Query:

select id,sentNum,message,sentTime,startAtTime,sentByTime,msgType,theGrp from
(   select id,sentNum,message,sentTime,startAtTime,sentByTime,msgType,theGrp,
    if(sentNum!=@lastSentNum,greatest(@sentNumChg:=1,0),least(@sentNumChg:=0,1)) as dummy1,
    if(theGrp!=@lastGrp,greatest(@grpChg:=1,0),least(@grpChg:=0,1)) as dummy2,
    if(@sentNumChg=1 or @grpChg=1,@seqNum:=1,@seqNum:=@seqNum+1) as seqNum,
    @lastSentNum:=sentNum as setLast01,
    @lastGrp:=theGrp as setLast02
    from
    (   -- GROUP 1: sentByTime<=now(), INVITE
        select `id`, `sentNum`, `message`, `sentTime`, `startAtTime`, `sentByTime`, `msgType`, 1 as theGrp
        from SmsQueue
        where sentByTime<=@theNow and msgType='invite'
        UNION ALL
        -- GROUP 2 startAtTime<=now(), BROADCAST
        select `id`, `sentNum`, `message`, `sentTime`, `startAtTime`, `sentByTime`, `msgType`, 2 as theGrp
        from SmsQueue
        where startAtTime<=@theNow and msgType='broadcast'
        UNION ALL
        -- GROUP 3: sentByTime>now() && startAtTime<=now(), INVITE
        select `id`, `sentNum`, `message`, `sentTime`, `startAtTime`, `sentByTime`, `msgType`, 3 as theGrp
        from SmsQueue
        where sentByTime>@theNow and startAtTime<=@theNow and msgType='invite'
    ) d1
    cross join (select @sentNumChg:=0,@grpChg:=0,@lastSentNum:='',@lastGrp:=0,@seqNum:=0) as xParams
    order by sentNum,theGrp,sentByTime,id -- id is the tie-break
) d2
where (theGrp=1 and seqNum<3) or (theGrp=2 and seqNum=1) or (theGrp=3 and seqNum=1)
order by sentNum,theGrp;

Output (my client tool is text challenged at the moment):

See my general comments at the top of this answer of mine for advanced variable usage.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!