您没有说是否还需要列出未注册任何课程的学生,因此我将提供另一种解决方案:
CREATE TABLE student (
sid NUMBER PRIMARY KEY,
sname VARCHAR2(40)
);
CREATE TABLE course (
cid NUMBER PRIMARY KEY,
cname VARCHAR2(40),
duration NUMBER,
fee NUMBER
);
CREATE TABLE enrolled (
sid NUMBER,
cid NUMBER,
PRIMARY KEY (sid, cid),
FOREIGN KEY (sid) REFERENCES student (sid),
FOREIGN KEY (cid) REFERENCES course (cid)
);
INSERT INTO student (sid, sname) VALUES (1, 'John');
INSERT INTO student (sid, sname) VALUES (2, 'Peter');
INSERT INTO student (sid, sname) VALUES (3, 'Jake');
INSERT INTO course (cid, cname, duration, fee) VALUES (1, 'Math', 1, 1000);
INSERT INTO course (cid, cname, duration, fee) VALUES (2, 'Physics', 1, 1500);
INSERT INTO enrolled (sid, cid) VALUES (1, 1); -- John taking Math
INSERT INTO enrolled (sid, cid) VALUES (1, 2); -- John taking Physics
-- Peter being lazy
INSERT INTO enrolled (sid, cid) VALUES (3, 1); -- Jake taking Math
COMMIT;
-- not taking lazy (not taking any courses) students under account
SELECT s.sid, MAX(c.fee)
FROM student s
JOIN enrolled e ON (e.sid = s.sid)
JOIN course c ON (e.cid = c.cid)
GROUP BY s.sid
;
-- all students
SELECT s.sid, NVL(MAX(c.fee), 0)
FROM student s
LEFT JOIN enrolled e ON (e.sid = s.sid)
LEFT JOIN course c ON (e.cid = c.cid)
GROUP BY s.sid
;