我有以下MySQL表。他们代表学校的CS课程,申请人是特定课程的助教(助教)。
我想创建一个查询,打印每个课程的“最佳”申请人。最佳申请人的限制是:
Applicants.level
= 7的申请人。ApplicantsToCourses.returning
= true的申请人为第二名。表定义是:
CREATE TABLE Courses (
course_number SMALLINT(3) UNSIGNED NOT NULL,
course_section SMALLINT(1) UNSIGNED NOT NULL,
name CHAR(30) NOT NULL,
instructor CHAR(30),
lab_time CHAR(30),
PRIMARY KEY(course_number, section),
FOREIGN KEY(course_number, section) REFERENCES ApplicantsToCourses(course_number, course_section)
)
CREATE TABLE Applicants (
student_id CHAR(10) NOT NULL,
name CHAR(30),
email CHAR(30),
gpa DECIMAL(4,3) UNSIGNED,
level CHAR(2),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(student_id),
FOREIGN KEY(student_id) REFERENCES ApplicantsToCourses(student_id),
CHECK(gpa <= 4.000)
)
CREATE TABLE ApplicantsToCourses (
student_id CHAR(10) NOT NULL,
returning BOOLEAN DEFAULT FALSE NOT NULL,
course_number SMALLINT(3) UNSIGNED NOT NULL,
course_section SMALLINT(1) UNSIGNED NOT NULL,
PRIMARY KEY(student_id, course_number, course_section),
FOREIGN KEY(student_id) REFERENCES Applicants(student_id),
FOREIGN KEY(course_number, course_section) REFERENCES Courses(course_number, course_section)
)
我对查询的尝试是。 。
select a.student_id, ac.course_number, ac.course_section
from Applicants a, ApplicantsToCourses ac, Courses c
where a.student_id = ac.student_id and ac.course_number = c.course_number and ac.course_section = c.course_section
order by a.level, ac.returning desc
。 。 。但那肯定没有正确的逻辑。
答案 0 :(得分:0)
您可以使用以下伪代码创建一些临时表,以帮助您找到最终解决方案。
SELECT *
FROM Applicants APP
JOIN ApplicantsToCourses ATC ON ATC.student_id = APP.student_id
JOIN Courses COU ON COU.number = ATC.course_number AND COU.section = ATC.course_section
WHERE APP.level = 7
SELECT *
FROM Applicants APP
JOIN ApplicantsToCourses ATC ON ATC.student_id = APP.student_id
JOIN Courses COU ON COU.number = ATC.course_number AND COU.section = ATC.course_section
WHERE ATC.returning = true