我有下表
id score start_time end_time
1 60 25 30
2 85 5 10
3 90 10 15
4 100 0 20
我想执行查询
SELECT * FROM table
WHERE the range between start_time and end_time doesn't overlap with anything in the result set ordered by score DESC
因此,在这种情况下,结果集将是:
id score start_time end_time
4 100 0 20
1 60 25 30
因为start_time
和end_time
的{{1}}和table.id =2
之间的范围与table.id =3
和start_time
之间的范围重叠{{1 } end_time
的{{1}}大于table.id =4
和score
的分数
是否可以通过mysql严格执行此操作?
答案 0 :(得分:3)
设置测试数据:
create table test(
id int,
score int,
start_time int,
end_time int
);
insert into test values
(5, 95, 0, 15), /*extra test case from me*/
(1, 60, 25, 30),
(2, 85, 5, 10),
(3, 90, 10, 15),
(4, 100, 0, 20)
;
需要的功能:
DELIMITER $$
DROP FUNCTION IF EXISTS checkOverlap$$
CREATE FUNCTION checkOverlap(p_id INT, p_score INT, p_stime INT, p_etime INT)
RETURNS BOOL
READS SQL DATA
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE result INT DEFAULT TRUE;
DECLARE stime, etime INT;
DECLARE cur1 CURSOR FOR SELECT start_time, end_time FROM test WHERE id != p_id AND score > p_score;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO stime, etime;
IF done THEN
LEAVE read_loop;
END IF;
IF ((p_stime >= stime AND p_stime <= etime) OR (p_etime >= stime AND p_etime <= etime)) THEN
SET result = FALSE;
END IF;
END LOOP;
CLOSE cur1;
RETURN result;
END$$
DELIMITER ;
如何使用该功能:
select *
from
test
where
checkOverlap(id, score, start_time, end_time) = TRUE
order by score desc
P.S:非常好的问题。很有趣解决