[英]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. 学生表具有父母ID作为外键,学生的状态可以为“已满”或“左”。 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. 我需要选择所有只有状态为“ LEFT”的学生的父母行-即,如果他们有两个学生,一个LEFT和一个FULL,则该父母将被忽略。
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.
我还考虑过让所有学生查询,然后以某种方式遍历结果并退出没有任何FULL学生的父母-但尚未成功。
Any help would be appreciated. 任何帮助,将不胜感激。
I am using PHP 我正在使用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. 我建议在父ID上以及
where
满学生为零的行上查询。 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. 一种简单的方法:您可以在子查询中分别提取“ left”和“ full”,并在没有“ full”条目的情况下进行左外部联接。
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 SQL Fiddle链接http://sqlfiddle.com/#!2/f4249c/6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.