Learning Session overlapping problems (3)-- Optimization
Follow the previous article
Http://blog.itpub.net/29254281/viewspace-2150229/
After thinking about the algorithm for a day and a half, the algorithm finally got the correct result last night.
In my environment, it takes 90 seconds and there is room for further optimization.
The preferred way is to generate T1 and T2.
The previous use of create table resulted in incorrect types
Because it is a temporary table, you can create the table structure in advance
CREATE TABLE `t1` (
`roomid` int (11) NOT NULL DEFAULT'0'
`userid`bigint (20) NOT NULL DEFAULT'0'
`s` timestamp
`e` timestamp
Primary KEY (`roomid`, `userid`, `s`, `e`)
KEY (`roomid`, `s`, `e`)
)
CREATE TABLE `t2` (
`roomid` int (11) NOT NULL DEFAULT'0'
`userid`bigint (20) NOT NULL DEFAULT'0'
`s` timestamp
`e` timestamp
Primary KEY (`roomid`, `userid`, `s`, `e`)
KEY (`roomid`, `s`, `e`)
)
The first step in the previous article can be encapsulated as a process
DELIMITER $$CREATE DEFINER= `root` @ `localhost`localhost` PROCEDURE `p` () BEGINinsert into t1select distinctroomid,userid,if (date (s)! = date (e) and id > 1 mai date (s+interval id-1 date (s+interval id-1 date (e), e date dated format (s+interval id-1'% localhost` Y-%m-%d 2359VR 59v 59') efrom (SELECT DISTINCT s.roomid, s.userid, s.s, (SELECT MIN (e) FROM (SELECT DISTINCT roomid,userid) Roomend AS eFROM u_room_log aWHERE NOT EXISTS (SELECT * FROM u_room_log bWHERE a.roomid = b.roomidAND a.userid = b.useridAND a.roomend > = b.roomstartAND a.roomend
< b.roomend)) s2WHERE s2.e >S.sAND s.roomid = s2.roomidAND s.userid = s2.userid) AS eFROM (SELECT DISTINCT roomid, userid, roomstart AS sFROM u_room_log aWHERE NOT EXISTS (SELECT * FROM u_room_log bWHERE a.roomid = b.roomidAND a.userid = b.useridAND a.roomstart > b.roomstartAND a.roomstart = b.roomstartAND a.roomend < b.roomend)) eWHERE s.roomid = e.roomidAND s.userid = e.userid) T1, numswhere nums.id=pTime and v2.s