简体   繁体   中英

mySQL Select if no matches in other table

I have two tables: Parent and Student

The student table has parent id as a foreign key, a student can have the status either FULL or LEFT. Multiple students can belong to one parent entry.

I need to select all parent rows that have ONLY students that have the status 'LEFT' - ie if they have two students, one LEFT and one FULL then this parent would be ignored.

I have tried a bunch of queries etc but not sure how to tackle this. I have also thought about getting all students as a query and then somehow looping through the result and pulling out the parents that don't have any FULL students - but haven't succeeded yet.

Any help would be appreciated.

I am using PHP

you can use exists and non exists to fetch only parents with left status in students table.

select * from parent p
where exists ( select 1 from student s
               where s.status ='LEFT'
               and s.parent_id = p.id
             )
and not exists ( select 1 from student s
               where s.status ='FULL'
               and s.parent_id = p.id
             )

I'd suggest joining the tables on the parent id and where 'ing the query on rows with zero full students. Something like this (untested):

SELECT [...] FROM parent LEFT JOIN student ON parent.id = student.pid
WHERE SUM(CASE WHEN student.status = 'full' THEN 1 ELSE 0 END) = 0

One poorly drawn diagram

在此处输入图片说明

In a simple way: You can extract 'left' and 'full' separately in a subquery and do the left outer join with no 'full' entry.

SELECT t1.p_id
    ,t1.STATUS
FROM (
    (
        SELECT p_id
            ,STATUS
        FROM student
        WHERE STATUS = 'left'
        ) t1 LEFT OUTER JOIN (
        SELECT p_id
            ,STATUS
        FROM student
        WHERE STATUS = 'full'
        ) t2 ON t1.p_id = t2.p_id
    )
WHERE t2.p_id IS NULL
GROUP BY t1.p_id
    ,t1.STATUS;

SQL Fiddle link http://sqlfiddle.com/#!2/f4249c/6

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