我有以下表格:
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');
如果我使用JOIN
IN
的{{1}}内容,我会得到相同的结果吗?
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';
感谢。
答案 0 :(得分: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';
(A select 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;