1

我有两个MySQL这样的表:

desc students;
+---------------------------+---------------+------+-----+---------+
| Field                     | Type          | Null | Key | Default |
+---------------------------+---------------+------+-----+---------+
| student_id                | int(11)       | NO   | PRI | NULL    |
| student_firstname         | varchar(255)  | NO   |     | NULL    |
| student_lasttname         | varchar(255)  | NO   |     | NULL    |
+---------------------------+---------------+------+-----+---------+

desc studentabsence;
+---------------------------+-------------+------+-----+---------+
| Field                     | Type        | Null | Key | Default |
+---------------------------+-------------+------+-----+---------+
| student_absence_id        | int(11)     | NO   | PRI | NULL    |
| student_id                | int(11)     | YES  |     | NULL    |
| student_absence_startdate | date        | YES  |     | NULL    |
| student_absence_enddate   | date        | YES  |     | NULL    |
| student_absence_type      | varchar(45) | YES  |     | NULL    |
+---------------------------+-------------+------+-----+---------+

然后我有这个MySQL- 查询列出学生。

询问:

SELECT s.student_id, s.student_firstname, s.student_lastname,
 a.student_absence_startdate, a.student_absence_enddate, a.student_absence_type
FROM students s LEFT JOIN studentabsence a ON a.student_id = s.student_id

每当学生有缺勤信息时,都会显示在列中

a.student_absence_startdate
a.student_absence_enddate
a.student_absence_type

有时一个学生在表格中有两行或更多行,studentabsence然后他被列出两次。

我的问题是是否有任何方法可以在查询中更具体。我想列出所有学生db.students 如果有db.studentabsence一个日期介于 startdate 和 enddate 之间的行(例如 2012-07-30),请使用此缺勤信息列出学生一次。仅当日期匹配时。

所以像...

... WHERE (a.student_absence_startdate OR a.student_absence_enddate) IS NULL OR
   '2012-07-30' BETWEEN a.student_absence_startdate AND
    a.student_absence_enddate ...

这有点难以解释,所以如果您需要更多信息,请告诉我......

4

2 回答 2

2

我认为您可以在子选择/子视图上使用 JOIN 来安排它:

SELECT s.student_id, s.student_firstname, s.student_lastname,
a.student_absence_startdate, a.student_absence_enddate, a.student_absence_type
FROM students s 
LEFT JOIN 
(SELECT * FROM studentabsence a1 WHERE ('2012-07-30' BETWEEN a1.student_absence_startdate AND a1.student_absence_enddate) ) a 
ON a.student_id = s.student_id
于 2012-07-30T14:44:07.467 回答
1

我会使用具有默认值的参数(01/01/1900 00:00:00),如下所示:

AND  ( a.student_absence_startdate >= @P_startdate  OR  @P_startdate = '01/01/1900 00:00:00' )  
AND  ( a.student_absence_enddate <= @P_enddate  OR  @P_enddate = '01/01/1900 00:00:00' )  
于 2012-07-30T14:49:17.870 回答