場景是,如果我有一張學生表,他們有 4 個班級,他們只知道房間號碼。還有兩張表,一張是老師姓名和房間號,另一張是老師姓名以及他們所教的科目。現在學生想知道誰是他們的數學老師,他們只想要學生姓名和數學老師姓名。
這是我正在從事的一個憑證專案的虛構場景。我已經讓它在很多情況下都能工作,但速度非常慢。用於建立新列的 case 條件沒有任何減慢速度,並且我使用相同的 case 條件左連接表,因為我們不知道將學生表與教師表關聯到哪一列。左連接中的情況條件似乎是造成麻煩的原因,我還可以使用其他任何方法來獲得相同的結果而不造成延遲嗎?
P粉5144588632024-02-27 00:26:59
我認為您遇到這麼多問題的原因是您的架構不太好。特別是學生表的架構,其中每個課程/房間號碼都有一列。
我先使用子查詢來修正這個問題,例如:
SELECT `Student Name`, 1 as Period, `1st Room#` as Room FROM students UNION ALL SELECT `Student Name`, 2 as Period, `2nd Room#` as Room FROM students UNION ALL SELECT `Student Name`, 3 as Period, `3rd Room#` as Room FROM students UNION ALL SELECT `Student Name`, 4 as Period, `4th Room#` as Room FROM students
像這樣的「Unpivoting」將為您提供一個漂亮乾淨的 Student Name |期間 | Room
架構將使解決這個問題變得更容易。
SELECT `Student Name`, Subject.`Teacher Name` FROM ( SELECT `Student Name`, 1 as Period, `1st Room#` as Room FROM students UNION ALL SELECT `Student Name`, 2 as Period, `2nd Room#` as Room FROM students UNION ALL SELECT `Student Name`, 3 as Period, `3rd Room#` as Room FROM students UNION ALL SELECT `Student Name`, 4 as Period, `4th Room#` as Room FROM students ) students INNER JOIN teacherRoom ON students.Room = teacherRoom.`Room Number` INNER JOIN teacherSubject ON teacherRoom.`Teacher Name` = teacherSubject.Subject WHERE teacherSubject.Subject = 'Math';