У меня есть следующий код - я впервые пытался использовать курсоры.
DELIMITER $$
DROP PROCEDURE IF EXISTS demo$$
DROP TABLE IF EXISTS temp$$
CREATE TEMPORARY TABLE temp(
id INTEGER NOT NULL AUTO_INCREMENT,
start DATETIME NOT NULL,
end DATETIME NOT NULL,
PRIMARY KEY(id)
) $$
CREATE PROCEDURE demo()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE a, b DATETIME;
DECLARE cur1 CURSOR FOR SELECT MAX(end) AS end
FROM (
SELECT id, start,
end,
@r := @r + (start > @edate) AS num,
@edate := GREATEST(@edate, end)
FROM (
SELECT @r := 0,
@edate := '0001-01-01'
) vars,
student_lectures
WHERE (
student_id = 1 AND
start >= '2010-04-26 00:00:00' AND
end <= '2010-04-30 23:59:59'
)
ORDER BY
start
) q
GROUP BY num;
DECLARE cur2 CURSOR FOR SELECT MIN(start) AS start
FROM (
SELECT id, start,
end,
@r := @r + (start > @edate) AS num,
@edate := GREATEST(@edate, end)
FROM (
SELECT @r := 0,
@edate := '0001-01-01'
) vars,
student_lectures
WHERE (
student_id = 1 AND
start >= '2010-04-26 00:00:00' AND
end <= '2010-04-30 23:59:59'
)
ORDER BY
start
) q
GROUP BY num
LIMIT 1, 18446744073709551615;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
OPEN cur2;
REPEAT
FETCH cur1 INTO a;
FETCH cur2 INTO b;
IF NOT done THEN
INSERT INTO temp(start, end) VALUES(a,b);
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
CLOSE cur2;
END $$
SELECT * FROM temp;
Я не получаю ничего, выводимого в таблицу temp
. Выполнение следующего запроса дает мне вывод, так что я знаю, что есть строки, которые должны совпадать, но я думаю, что допустил очевидную ошибку.
SELECT MAX(end) AS end
FROM (
SELECT id, start,
end,
@r := @r + (start > @edate) AS num,
@edate := GREATEST(@edate, end)
FROM (
SELECT @r := 0,
@edate := '0001-01-01'
) vars,
student_lectures
WHERE (
student_id = 1 AND
start >= '2010-04-26 00:00:00' AND
end <= '2010-04-30 23:59:59'
)
ORDER BY
start
) q
GROUP BY num;
Вывод этого запроса возвращает:
+---------------------+
| end |
+---------------------+
| 2010-04-26 13:00:00 |
| 2010-04-26 18:15:00 |
| 2010-04-27 11:00:00 |
| 2010-04-27 13:00:00 |
| 2010-04-27 18:15:00 |
| 2010-04-28 13:00:00 |
| 2010-04-29 13:00:00 |
| 2010-04-29 18:15:00 |
| 2010-04-30 13:00:00 |
| 2010-04-30 15:15:00 |
| 2010-04-30 17:15:00 |
+---------------------+
11 rows in set (0.02 sec)