mySQL-仅选择连续出现的记录
我正在制作一张处理学生记录的表格。基本上,我只需要选择至少连续3个未注册学期的学生的记录 样本数据:mySQL-仅选择连续出现的记录,mysql,Mysql,我正在制作一张处理学生记录的表格。基本上,我只需要选择至少连续3个未注册学期的学生的记录 样本数据: StudentID|Unregistered|Semester 10000000 |Y |1 10000000 |Y |2 10000000 |Y |6 10000001 |Y |2 10000001 |Y |8 10000001 |Y |9 10000001 |Y
StudentID|Unregistered|Semester
10000000 |Y |1
10000000 |Y |2
10000000 |Y |6
10000001 |Y |2
10000001 |Y |8
10000001 |Y |9
10000001 |Y |10
10000002 |Y |1
10000002 |Y |2
10000002 |Y |3
10000002 |Y |10
我只想从学生ID 10000001和10000002中选择记录。以下查询将为您提供连续学期的计数:
select s.id,
if(s.semester = @previousSem + 1 and @previousId = s.id,
@count := @count + 1, @count := 1) as count,
@previousSem := s.semester as sem,
@previousId := s.id as previousId
from sample s, (SELECT
@count := 1,
@previousSem := -1,
@previousId := 0) a
order by s.id, s.semester
现在,您需要将此查询
与主表(self-join
)连接起来,并过滤出具有3个或更多计数的记录,例如:
select s.id
from sample s join (select s.id,
if(s.semester = @previousSem + 1 and @previousId = s.id,
@count := @count + 1, @count := 1) as count,
@previousSem := s.semester as sem,
@previousId := s.id as previousId
from sample s, (SELECT
@count := 1,
@previousSem := -1,
@previousId := 0) a
order by s.id, s.semester) s1
on s.id = s1.id
where s1.count >= 3
group by s.id;
这是
p.S.删除
unregistered
列为简洁起见,您可以在实际查询中添加它,并在内部查询中添加WHERE
条件(WHERE registered='Y'
)。而且它不使用会话变量(它们是邪恶的):
更灵活的解决方案是:
set @num = 3;
select distinct r1.StudentID
from registrations r1
join registrations r2
on r2.StudentID = r1.StudentID
and r2.Semester > r1.Semester
and r2.Semester <= r1.Semester + @num - 1
where r1.Unregistered = 'Y'
and r2.Unregistered = 'Y'
group by r1.StudentID, r1.Semester
having count(*) = @num - 1
set@num=3;
选择不同的r1.StudentID
来自注册r1
加入注册r2
在r2.StudentID=r1.StudentID上
r2.学期>r1.学期
和r2。我们可以看到(幸运的是,它们都未注册)的可能副本
set @num = 3;
select distinct r1.StudentID
from registrations r1
join registrations r2
on r2.StudentID = r1.StudentID
and r2.Semester > r1.Semester
and r2.Semester <= r1.Semester + @num - 1
where r1.Unregistered = 'Y'
and r2.Unregistered = 'Y'
group by r1.StudentID, r1.Semester
having count(*) = @num - 1