简而言之,找到迈克可以在下学期学习CS课程代码的查询。
结果应如下所示:
Code
----
IE2700
IE3200
以下是包含示例数据的数据库表:
学生
Sid Name
---------- ----------
2 Kathlyn
6 Mike
7 Nick
9 Anny
课程
Code Title Dept Credits
---------- ----------- ---------- ----------
IE1100 programming CS 10
IE2201 operating s CS 20
IE2700 database CS 10
IE2900 software en CS 10
IE3200 distributed CS 10
MAT1001 calculus Math 30
DOK1012 database Hum 10
CoursesBuiltOn
Code BuiltOn
---------- ----------
IE2201 IE1100
IE2700 IE1100
IE2900 IE2201
IE2900 IE2700
IE3200 IE2201
等级
Sid Code Year Grade
---------- ---------- ---------- ----------
2 MAT1001 2010 A
2 IE1100 2011 A
2 IE2201 2012 A
2 IE2700 2013 A
2 IE2900 2014 B
2 IE3200 2014 B
6 MAT1001 2011 D
6 IE1100 2012 C
6 IE2201 2013 B
6 IE2700 2013 F
7 MAT1001 2013 B
7 DOK1012 2013 A
9 MAT1001 2013 F
数据库结构:
CREATE TABLE Students (
Sid TEXT PRIMARY KEY,
Name TEXT
);
CREATE TABLE Courses (
Code TEXT PRIMARY KEY,
Title TEXT,
Dept TEXT,
Credits INT
);
CREATE TABLE Grades (
Sid INT,
Code TEXT,
Year INT,
Grade TEXT,
PRIMARY KEY (Sid, Code),
FOREIGN KEY (Sid) REFERENCES Students (Sid),
FOREIGN KEY (Code) REFERENCES Courses (Code)
);
CREATE TABLE CoursesBuiltOn (
Code TEXT,
BuiltOn TEXT,
PRIMARY KEY (Code, BuiltOn),
FOREIGN KEY (Code) REFERENCES Courses (Code),
FOREIGN KEY (Code) REFERENCES Courses (BuiltOn)
);
我尝试将所有表格连接在一起以获取外键并获取信息,但我找不到任何方法来获得正确的答案。
这是我到目前为止所得到的:
with NotAvailable as (select COB.Code
from Courses C
left join CoursesBuiltOn COB on COB.BuiltOn = C.Code
left join Grades Gr on Gr.Code = C.Code
inner join Students S on S.Sid = Gr.Sid
where Gr.Sid = S.Sid and Gr.Grade = 'F'
), AlreadyTakenAndPassed as (select Gr.Code
from Grades Gr where Gr.Sid = S.Sid and Gr.Grade <> 'F'
), TakenButNotYetPassed as (select Gr.Code
from Grades Gr where Gr.Sid = S.Sid and Gr.Grade = 'F'
)
select COB.Code
from Courses C
left join CoursesBuiltOn COB on COB.BuiltOn = C.Code
left join Grades G on G.Code = C.Code
inner join Students S on G.Sid = S.Sid
where C.Dept = 'CS' and S.Name = 'Mike'
and (COB.Code in TakenButNotYetPassed or COB.Code not in NotAvailable or COB.Code not in AlreadyTakenAndPassed)
;
Code
----------
IE2700
IE2900
IE3200
IE2900
select COB.Code
from Courses C
left join CoursesBuiltOn COB on COB.BuiltOn = C.Code
left join Grades G on G.Code = C.Code
inner join Students S on S.Sid = G.Sid
where S.Name = 'Mike' and G.Grade = 'F';
Code
----------
IE2900
正如您在上面的查询中所看到的,我想创建子查询,从整个课程集中排除课程。但是,NotAvailable
子查询不会排除IE2900
。这是为什么?我以为我是在正确的方向......这可能不是最有效的方式触摸...
答案 0 :(得分:0)
我自己做了,将整个查询切入案例:
with
TakenButNotYetPassed as (select Gr.Code
from Grades Gr
inner join Students St on St.Sid = Gr.Sid
where St.Name = 'Mike' and Gr.Grade = 'F'
),
NotAvailable as (select Code
from CoursesBuiltOn
where BuiltOn in TakenButNotYetPassed
),
Passed as (select Gr.Code
from Grades Gr
inner join Students St on St.Sid = Gr.Sid
where St.Name = 'Mike' and Gr.Grade <> 'F'
)
select *
from Courses C
where C.Dept = 'CS'
and C.Code not in Passed
and C.Code not in NotAvailable
;