简体   繁体   中英

SQL : Select a parent record if all values in a child table are FALSE

I'm having this problem with my query : I'm trying to get all the records from the parent table when ALL the values of the children table are either nonexistant or FALSE.

The tables look like this :

Admission (parent table)            Courses (child table)
------------------------            ---------------------
IDAdmission                         IDCourse
[Other data]                        IDAdmission 
                                    CourseCompleted
                                    [Other data]

Where one admission can have multiple (or none) courses.

For instance, if my query was

SELECT Admission.IDAdmission, Courses.IDCourse, Courses.IDAdmission,
Courses.CourseCompleted FROM Admission LEFT OUTER JOIN Courses ON 
Admission.IDAdmission = Courses.IDAdmission

I would obtain the following records :

Admission           Courses
IDAdmission         IDCourse    IDAdmission    CourseCompleted
--------------------------------------------------------------
123                 001         123            false
123                 002         123            true
456                 001         456            false
456                 004         456            false
456                 006         456            false
789                 002         789            true
789                 006         789            false
345                 NULL        NULL           NULL

Now, what I'm looking for is to get the records from the parent table Admission ONLY if all the CourseCompleted criteria is false. If the criteria is NULL , it should also be selected.

Therefore, from the above data, I'd like to select the following from the parent table Admission :

IDAdmission
-----------
456
345

I'm trying to get this information out in a report, therefore I cannot use temporary tables. I've looked into Anti-Join, but I'm not sure it would solve my issue (or perhaps, I misunderstood their usefulness in this situation).

Any help in this matter would be greatly appreciated. Thank you!

You can use a sub-query within EXISTS to exclude all the admission recrods with at least 1 completed course.

SELECT
    Admission.IDAdmission
FROM Admission
WHERE NOT EXISTS (
    SELECT * FROM Courses C2
    WHERE C2.IDAdmission = Admission.IDAdmission
        AND C2.CourseCompleted = 'true'
)

This should work:

select a.IDAdmission 
from Admission a 
where not exists (select 1 from Courses c 
                  where c.IDAdmission =  a.IDAdmission 
                  and c.CourseCompleted = true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM