如何处理子查询返回null

时间:2018-07-31 18:01:20

标签: mysql sql select subquery

如果子选择不为空,我只想运行父选择。不确定如何使用sql查询来实现这一目标:-

SELECT * from schools 
    WHERE `district_id` =
    (SELECT district_id from schools WHERE `school_id` = '0023194')

3 个答案:

答案 0 :(得分:1)

您应该像...一样运行您的sql查询。

SELECT * from schools 
WHERE `district_id` = 
(SELECT district_id from schools 
    WHERE `school_id` = '0023194'
    AND 
    district_id IS NOT NULL) 
AND district_id IS NOT NULL
  

district_id不为空   防止district_id不为空

答案 1 :(得分:1)

似乎您只需要使用IN,如下所示:

SELECT * from schools 
WHERE `district_id` in
(SELECT district_id from schools WHERE `school_id` = '0023194')

SQL HERE

答案 2 :(得分:1)

您可以使用IN运算符,因为IN运算符允许您在WHERE子句中指定多个值。

IN运算符是多个OR条件的简写。在您的条件下,=仅比较一个条件,但是如果您有此school_id的多个记录,则=无法对其进行评估。

SELECT * from schools WHERE `district_id` in (SELECT district_id from schools WHERE `school_id` = '0023194')