0

我有以下表格:

students (studentid, firstname, lastname)
finals (studentid, subjectid, finaldate, mark)
subjects (subjectid, subjectname, semester)

我需要知道参加数据库期末考试的学生(出示身份证)。我做了以下事情:

select studentid
from finals
where subjectid in (select subjectid
                    from subjects
                    where subjectname = 'database');

如果我使用JOINinsted of会得到相同的结果IN吗?

select studentid
from finals f, subjects s
where f.subjectid = s.subjectid
and s.subjectname = 'database';

如果我需要了解从未参加过数据库期末考试的学生(出示身份证)怎么办?

这样做是不是一样...

select studentid
from finals
where subjectid not in (select subjectid
                        from subjects
                        where subjectname = 'database');

...比这个?

select studentid
from finals f, subjects s
where f.subjectid = s.subjectid
and s.subjectname <> 'database';

谢谢。

4

1 回答 1

0

您的第一个问题的答案通常是“是”,但您应该使用正确的连接语法:

select studentid
from finals f join
     subjects s
     on f.subjectid = s.subjectid and s.subjectname = 'database';

这通常是因为subjects表中的重复项会出现在join版本中而不是in版本中。严格的等价物是:

select studentid
from finals f join
     (select distinct subjectid, subjectname
      from subjects s
     ) s
     on f.subjectid = s.subjectid and s.subjectname = 'database';

(Aselect distinct studentid很接近,但finals如果存在,它将消除表中的重复项。)

第二个答案是“不”。正确的查询是left outer join一个where过滤器,只获取不匹配的行:

select studentid
from finals f left outer join
     subjects s
     on f.subjectid = s.subjectid and s.subjectname = 'database'
where s.subjectid is not null;
于 2013-09-18T03:52:35.730 回答