IN()中的嵌套查询未产生期望的结果

时间:2018-08-24 15:30:44

标签: sql

我有一个学生表(学生)和学生关系表(Student_PARTY)。 我想获取具有“朋友”和“家庭”两个关系的学生的详细信息。为此,我编写了以下查询。但是,尽管我有这样的数据,它总是返回空结果。

select name, id
from party
where type = 'Student' and
      id in (select distinct stu_id2
             from Student_PARTY
             where rel_type = 'Friend' and
                   stu_id2 in (select stu_id2 from Student_PARTY where rel_type='Family'
                               )
            )

3 个答案:

答案 0 :(得分:0)

尝试使用 INNER JOIN 来过滤所需的内容。

SELECT DISTINCT
    party.name,
    party.id
FROM
    party
    INNER JOIN Student_PARTY spfr
    ON party.id = spfr.stu_id2
    AND spfr.rel_type = 'Friend'
    INNER JOIN Student_PARTY spfam
    ON party.id = spfam.stu_id2
    AND spfam.rel_type = 'Family'
WHERE
    party.type = 'Student'

EXISTS()

SELECT DISTINCT
    party.name,
    party.id
FROM
    party
WHERE
    party.type = 'Student'
    AND EXISTS(
                SELECT x.stu_id2
                FROM Student_PARTY x
                WHERE
                    x.rel_type = 'Friend'
                    AND x.stu_id2 = party.id
              )
    AND EXISTS(
                SELECT x.stu_id2
                FROM Student_PARTY x
                WHERE
                    x.rel_type = 'Family'
                    AND x.stu_id2 = party.id
              )

答案 1 :(得分:0)

我改用exists

select p.name, p.id
from party p
where type = 'Student' and
      exists (select 1 from Student_PARTY sp where sp.stu_id2 = p.id and sp.rel_type = 'Friend') and  
      exists (select 1 from Student_PARTY sp where sp.stu_id2 = p.id and sp.rel_type = 'Family');

答案 2 :(得分:0)

您的第一个IN

select stu_id2 from Student_PARTY where rel_type = 'Friend' 

您的第二个IN

select stu_id2 from Student_PARTY where rel_type = 'Family'

我删除了没做任何事情的distinct并进行了格式化,但是您能看到问题吗?通常没有任何结果,因为rel_type不能同时等于“朋友”和“家人”。我的猜测是您的一个字段名称中有错字,可能其中stu_id2的其中一个并不是stu_id2