MySQL连续缺席

时间:2010-05-13 20:10:27

标签: mysql

我的数据库中有2个表:学生和缺席。在学生中:id_student,s_name;在缺席的情况下:id_student,日期,日期(作为数字的星期几 - 它不是那么重要); 我想让那些连续缺席超过2天的学生和日期。

目前我有下一个查询:

 /*To control when the days are in the same week*/  
SELECT id_student, date, dayname(date),date_add(date, INTERVAL 1 DAY) AS a,  
 dayname(date_add(date, INTERVAL 1 DAY)) AS an, date_add(date, INTERVAL 2 DAY) AS b,  
 dayname(date_add(date, INTERVAL 2 DAY)) AS bn  
FROM absences AS a  
WHERE id_student IN  
                (SELECT id_student FROM absences   
                  WHERE id_student = a.id_student  
                  AND date = date_add(a.date, INTERVAL 1 DAY) )  
AND id_student IN  
               (SELECT id_student FROM absences  
                 WHERE id_student = a.id_student  
                 AND date = date_add(a.date,INTERVAL 2 DAY) )  
UNION  
/*To control when the days jump to the next week*/  
SELECT id_student, date, dayname(date),date_add(date, INTERVAL 3 DAY) AS a,  
 dayname(date_add(date, INTERVAL 3 DAY)) AS an, date_add(date, INTERVAL 4 DAY) AS b,  
 dayname(date_add(date, INTERVAL 4 DAY)) AS bn  
FROM absences AS a  
WHERE id_student IN  
               (SELECT id_student FROM absences  
                 WHERE id_student = a.id_student  
                  AND date = date_add(a.date, INTERVAL 3 DAY) )  
AND id_student IN  
                (SELECT id_student FROM absences  
                  WHERE id_student = a.id_student  
                  AND date = date_add(a.date,INTERVAL 4 DAY) )  
/* To avoid the case (Monday-Thursday-Friday) to be consider as consecutive days*/  
AND WEEKDAY(date) !=0   

此刻我得到了那样的话:

3000000 2010-05-10  Monday  2010-05-11  Tuesday         2010-05-12  Wednesday 
3000000 2010-05-11  Tuesday 2010-05-12  Wednesday     2010-05-13    Thursday 
3000000 2010-05-07  Friday  2010-05-10  Monday          2010-05-11  Tuesday 
3000001 2010-05-14  Friday  2010-05-17  Monday          2010-05-18  Tuesday

但它显示连续几天的分组列表为3天。我想更加类似于此:

3000000 2010-05-10  Monday  2010-05-11  Tuesday         2010-05-12  Wednesday  2010-05-13   Thursday 
3000000 2010-05-07  Friday  2010-05-10  Monday          2010-05-11  Tuesday 
3000001 2010-05-14  Friday  2010-05-17  Monday          2010-05-18  Tuesday

谢谢

1 个答案:

答案 0 :(得分:0)

这不是完整的解决方案,而且此查询未经测试,但它演示了如何使用自联接获得一系列三次或更多次缺席的第一条记录:

SELECT a.id_student, a.date, DAYNAME(a.date) FROM absences a
JOIN absences a2
ON a2.id_student = a.id_student AND (a2.date = date_add(a.date, INTERVAL 1 DAY) OR (DAYNAME(a.date) = 'Friday' AND a2.date = date_add(a.date, INTERVAL 3 DAY)))
JOIN absences a3
ON a3.id_student = a.id_student AND (a3.date = date_add(a2.date, INTERVAL 1 DAY) OR
(DAYNAME(a3.date) = 'Friday' AND a3.date = date_add(a2.date, INTERVAL 3 DAY)))
LEFT JOIN absences a4
ON a4.id_student = a.id_student AND (a4.date = date_add(a.date, INTERVAL -1 DAY) OR
(DAYNAME(a4.date) = 'Monday' AND a4.date = date_add(a.date, INTERVAL -3 DAY)))
WHERE a4.id_student IS NULL

您使用连接来获取序列,并使用左连接仅获取前一天没有缺席的记录以获取第一条记录。