MYSQL 连续性问题求解
问题:
使用SQL查找学生的成绩表(表名;grade,列名;序号,成绩)中至少连续出现3次的成绩。
create table grade(
num smallint not null,
score int(3) not null);
insert into grade values
(1,89),
(2,76),
(3,76),
(4,84),
(5,84),
(6,84),
(7,76),
(8,76),
(9,76);
方法一:使用多个自连表来实现
不足:当查找的连续值过多时,运行效率过低
select distinct(a.score) from grade as a, grade as b, grade as c
where a.score = b.score and b.score = c.score
and a.num = b.num + 1 and b.num = c.num+ 1
;
方法二:构造一个等差数列,利用差值来查找
使用的技巧:@rn声名变量,@rn := @rn + 1 构造一个等差数列,(select @rn := 10)as a ,给声名的变量一个初始值,为10
as a,是因为必须要给该临时表一个别名
select score from
(
select num, score, @rn := @rn + 1 as nump from grade,
(select @rn := 10) as a
order by score
) as b
group by (b.num - b.nump), score
having count(b.num - b.nump) > 2
;
扩展:
查找下表中连续夺冠的球队,及开始和结束的时间
±---------±-----+
| team | year |
±---------±-----+
| 活塞 | 1990 |
| 公牛 | 1991 |
| 公牛 | 1992 |
| 公牛 | 1993 |
| 火箭 | 1994 |
| 火箭 | 1995 |
| 公牛 | 1996 |
| 公牛 | 1997 |
| 公牛 | 1998 |
| 马刺 | 1999 |
| 湖人 | 2000 |
| 湖人 | 2001 |
| 湖人 | 2002 |
| 马刺 | 2003 |
| 活塞 | 2004 |
| 马刺 | 2005 |
| 热火 | 2006 |
| 马刺 | 2007 |
| 凯尔特人 | 2008 |
| 湖人 | 2009 |
| 湖人 | 2010 |
±---------±-----+
select team, min(year), max(year) from
(
select team, year, @rn := @rn + 1, (year - @rn) as y_cha
from (select @rn := 1990) as argu, nba
order by team
) as t
group by team, y_cha
having count(y_cha) > 1;
来源:oschina
链接:https://my.oschina.net/u/4398725/blog/4540098