I am retrieving all records from a table based on two exclusive conditions. Each record is duplicated, with the duplicate record having a separate flag isWaitList = 1, and the parent storing the primary ID of its child stored in field waitListProdID; child records will have a 0 in their waitListProdID field since they cannot have their own children (i.e. child elements only go one level deep).
The table's relevant rows are conferenceID (int), [description] (varchar), maxAttendance (int), currentAttendance (int), isWaitlist (bit), waitListProdID (int)
.
The conditions are:
- Retrieve parent/child if currentAttendance < maxAttendance (universal)
- Retrieve child ONLY if its parent row satisfies currentAttendance >= maxAttendance
This union does the trick, though I'm wondering if A) I have written it efficiently enough, and B) if this would better served as a single (if more complex) query?
SELECT conferenceID, [description]
FROM tblEventConferences
WHERE currentAttendance < maxAttendance
AND isWaitList = 0
AND eventID = 624
UNION
SELECT conferenceID, [description]
FROM tblEventConferences
WHERE isWaitlist = 1
AND currentAttendance < maxAttendance
AND conferenceID NOT IN (
SELECT waitlistProdID
FROM tblEventConferences
WHERE isWaitList = 0
AND eventID = 624
AND currentAttendance < maxAttendance
)