SELECT行由两个字段(开始 - 结束)指定的数值范围与任何其他行中指定的范围不重叠

时间:2012-03-29 08:54:41

标签: mysql

我有下表

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_timeend_time的{​​{1}}和table.id =2之间的范围与table.id =3start_time之间的范围重叠{{1 } end_time的{​​{1}}大于table.id =4score的分数

是否可以通过mysql严格执行此操作?

1 个答案:

答案 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:非常好的问题。很有趣解决