2010-11-18 49 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