Putting more conditions in the join

For a basic introduction to joins, click here 

I have the following table, called tblSchool:

lSchoolID

sSchool

bActive
1 dowclerkoo memorial school -1
2 kwevonuh girls high school 0

If the names seem strange, it is because my test data was generated automatically.

A value of -1 in the bActive column, indicates that the school is open and accepting new enrolments. A value of 0 indicates that the school has been closed.

I also have the following table of students:

lStudentID

sName

lSchoolID
40001 Gina 1
40002 Robert 1
40003 Jane 2
40004 Simon NULL

Jane is enrolled in a school which has been closed (perhaps it burnt down after she was enrolled).

Simon has not been enrolled in a school at all.

The following query will return a list of all students and the schools at which they are enrolled:

SELECT tblStudent.*, tblSchool.sSchool
FROM tblStudent LEFT JOIN tblSchool
ON tblStudent.lSchoolID=tblSchool.lSchoolID

lStudentID

sName

lSchoolID sSchool
40001 Gina 1 dowclerkoo memorial school
40002 Robert 1 dowclerkoo memorial school
40003 Jane 2 kweevonuh girls high school
40004 Simon NULL NULL

Since kweevonuh girls high school has been closed, I don't want it to appear on this list.

I could set lSchoolID to NULL on Jane's record, but I don't want to throw away the knowledge that she WAS enrolled at kweevonuh.

That information could be important, because I may later want to run an UPDATE query, to move all the students who WERE enrolled at kweevonuh, to another school. Or it might be possible that the school will be reopened.

One way of getting what I want, would be to use a CASE expression in the SELECT list:

SELECT tblStudent.*,
CASE WHEN tblSchool.bActive=-1
    THEN tblSchool.sSchool
    ELSE NULL END
FROM tblStudent LEFT JOIN tblSchool
    ON tblStudent.lSchoolID=tblSchool.lSchoolID

This second query will return the following records:

lStudentID

sName

lSchoolID sSchool
40001 Gina 1 dowclerkoo memorial school
40002 Robert 1 dowclerkoo memorial school
40003 Jane 2 NULL
40004 Simon NULL NULL

Today's more obscure tip, is that it is possible to get exactly the same result by adding an extra condition to the join expression:

SELECT tblStudent.*, tblSchool.sSchool
FROM tblStudent LEFT JOIN tblSchool
ON tblStudent.lSchoolID=tblSchool.lSchoolID
AND tblSchool.bActive=-1
ORDER BY tblStudent.lStudentID

This query works much like an ordinary LEFT JOIN, except that records from tblSchool are only joined if bActive=-1.

Adelle.

Home About the Author Copyright © 2001 Adelle Hartley