所以我们有一个时间码表,为了争论,可能看起来像这样......
CREATE TABLE timecodes(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,timecode INT NOT NULL);
INSERT INTO timecodes (timecode) VALUES (2),(3),(4),(4),(6),(13),(14),(17),(18),(18),(21),(25),(28),(28);
SELECT * FROM timecodes;
+----+----------+
| id | timecode |
+----+----------+
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 4 | 4 |
| 5 | 6 |
| 6 | 13 |
| 7 | 14 |
| 8 | 17 |
| 9 | 18 |
| 10 | 18 |
| 11 | 21 |
| 12 | 25 |
| 13 | 28 |
| 14 | 28 |
+----+----------+
现在,这个问题分为两部分。第一部分涉及从前n 个结果中获取随机结果。这样做的一种方法(尽管可能不是最快的方法)是这样的......
SELECT @seed := x.timecode
FROM timecodes x
JOIN timecodes y
ON y.id <= x.id
GROUP
BY x.id
HAVING COUNT(*) <= 5
ORDER
BY RAND()
LIMIT 1;
+---------------------+
| @seed := x.timecode |
+---------------------+
| 4 |
+---------------------+
此查询生成一个种子(在本例中为“4”),可以将其返回到后续查询中,例如;
SELECT @seed := MIN(y.timecode)
FROM timecodes x
JOIN timecodes y
ON y.timecode >= x.timecode + 3
WHERE x.timecode = @seed;
1st iteration
+--------------------------+
| @seed := MIN(y.timecode) |
+--------------------------+
| 13 |
+--------------------------+
2nd iteration
+--------------------------+
| @seed := MIN(y.timecode) |
+--------------------------+
| 17 |
+--------------------------+
3rd iteration
+--------------------------+
| @seed := MIN(y.timecode) |
+--------------------------+
| 21 |
+--------------------------+
4th iteration
+--------------------------+
| @seed := MIN(y.timecode) |
+--------------------------+
| 25 |
+--------------------------+
5th iteration
+--------------------------+
| @seed := MIN(y.timecode) |
+--------------------------+
| 28 |
+--------------------------+
6th iteration
+--------------------------+
| @seed := MIN(y.timecode) |
+--------------------------+
| NULL |
+--------------------------+
这可以包含在一个存储过程中,或者一些应用程序级别的代码中,上面写着“然后做第一件事,而 @seed 不是 NULL,做第二件事”——但这超出了我的薪酬等级。