David
David

Reputation: 1191

MySQL query to select dates where field is NULL or field date value is not greater than another date

I have this MySQL query:

SELECT DISTINCT
    *
FROM
    students s
        LEFT JOIN
    (SELECT 
        *
    FROM
        studentabsences a1
    WHERE
        (a1.absence_date = '2013-01-28')) a ON a.absence_student_id = s.student_id
        LEFT JOIN
    (SELECT 
        *
    FROM
        studentabsencenotes b1
    WHERE
        (b1.absence_note_date = '2013-01-28')
    GROUP BY absence_note_student_id) b ON b.absence_note_student_id = s.student_id
        INNER JOIN
    studentdates sd ON sd.student_id = s.student_id
        INNER JOIN
    coursecategory ctc ON s.student_course_category_id = ctc.category_id
WHERE
    '2013-01-28' BETWEEN sd.student_startdate AND sd.student_enddate
ORDER BY s.student_lastname , s.student_firstname

Now I would like to add another WHERE clause to select rows that has not a greater sd.student_break_date than 2013-01-28 but also select empty fields

For example:

WHERE '2013-01-28' >= sd.student_break_date

This works but those rows that has NULL values in the sd.student_break_date are not listed.

Messy, huh? My question is: How can I select fields that are empty AND fields where date is not higher than 2013-01-28

Upvotes: 2

Views: 18079

Answers (2)

Dave
Dave

Reputation: 3288

BETWEEN is an odd one for this bit of code

'2013-01-28' BETWEEN sd.student_startdate AND sd.student_enddate

You're actually doing sd.student_startdate>'2013-01-28' AND sd.student_enddate<'2013-01-28'. Notice there's no = in there so its actually excluding the 28th in both cases. If you want to actually include the 28th in your clause then a BETWEEN is not really any use.

As for you're question assuming the badly worded question means you want an sd.studen_break_date which is either null or less than the 28th then it'd be

WHERE sd.student_startdate>'2013-01-28' AND sd.student_enddate<'2013-01-28' AND (sd.student_break_date is null OR sd.student_break_date<='2013-01-28')

Upvotes: 1

Sashi Kant
Sashi Kant

Reputation: 13465

Try this ::

WHERE sd.student_break_date is null OR  '2013-01-28' >= sd.student_break_date

OR you can try ::

WHERE sd.student_break_date is null OR  sd.student_break_date<'2013-01-28'

OR ::

WHERE IFNULL(sd.student_break_date,'2013-01-27') <'2013-01-28'

Upvotes: 2

Related Questions