从一个数据表中找出连续n条满足条件的记录
例子demo 从数据表中找出连续三条或者三次以上分数超过80分的记录
MariaDB [testdatabase]> select * from class; +----+-----------+---------+-------+ | id | classname | teacher | grade | +----+-----------+---------+-------+ | 0 | 101 | peter | 85 | | 1 | 102 | john | 86 | | 2 | 103 | tom | 87 | | 3 | 104 | mango | 88 | | 4 | 101 | peter | 65 | | 5 | 106 | peter | 95 | | 6 | 105 | haden | 96 | | 7 | 107 | james | 77 | | 8 | 108 | jakie | 88 | | 9 | 109 | tom | 85 | | 10 | 112 | mango | 76 | | 11 | 113 | jula | 77 | | 12 | 114 | john | 78 | +----+-----------+---------+-------+
SQL语句如下
select * from class where id in (
select DISTINCT n1.id from class n1,class n2,class n3 where
(n1.grade>80 and n2.grade>80 and n3.grade>80 and
((n1.id + 1= n2.id and n2.id +1 = n3.id) OR
(n1.id-1=n2.id and n1.id+1=n3.id) OR
(n1.id-1=n2.id and n1.id-2=n3.id) )
) order by n1.id )
输出结果
+----+-----------+---------+-------+
| id | classname | teacher | grade |
+----+-----------+---------+-------+
| 0 | 101 | peter | 85 |
| 1 | 102 | john | 86 |
| 2 | 103 | tom | 87 |
| 3 | 104 | mango | 88 |
+----+-----------+---------+-------+