2012-07-30 179 views
1

之間匹配的日期和空我有兩個MySQL -tables這樣的: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中有一行日期在開始日期和結束日期之間(例如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 ... 

這是有點難以解釋,所以讓我知道如果你需要更多信息...

回答

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 
+0

完美。非常感謝你。 – David 2012-07-30 14:57:54

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') 
+0

謝謝你的回覆,但是我用@aleroot建議去了! – David 2012-07-30 14:58:13