2010-11-18 18 views
0

我有以下MySQL表格。他们代表学校的CS课程,申请人是特定课程的TA(助教)。通过MySQL查询选择职位申请人

我想创建一个查询,打印每个课程的“最佳”申请人。最佳申请人的限制条件如下:

  1. 申请人Applicants.level = 7首先匹配。
  2. 具有ApplicantsToCourses.returning = true的申请人被选中第二位。
  3. 所有其他申请人无需进一步歧视匹配。

表的定义是:

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

这是一门功课的问题吗?您的查询以何种方式不正确?它显示的结果有什么问题? – 2010-11-18 17:58:53

回答

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