背景是學生可以選擇不同的班級,設定權重并選擇一個班級的老師(選擇A,B,C,D),一個班級有四個老師。
表格如下
class:
id integer
name string
description string
student:
id integer
name string
student_choice:
id integer
class_id integer
student_id integer
weight decimal
choice string
teacher:
id integer
class_id integer
choice string
teacher_desc string
我想要做的是通過他/她的 id 獲得學生的所有選擇,結果看起來像這樣
| 班級號 | 班級名稱 | 重量 | 選擇 | 教師描述 |
|---|---|---|---|---|
| 1 | 數學 | 0.2 | 一種 | 愛麗絲 |
| 3 | 音樂 | 0.5 | 乙 | 鮑勃 |
| 4 | 身體的 | 0.3 | 一種 | 艾倫 |
目前我只是使用 student_choice 表查找學生選擇的所有課程,并找到與學生選擇對應的老師
student.id --> student_choice --> class.id
class.id student_choice.choice --> teacher
我不知道是否可以只用一個 SQL 查詢來實作這一點,所以我只使用多個查詢并在我的應用程式中處理它們。
誰能告訴我我應該怎么做才能只用一個 SQL 查詢來實作我的目的,或者只是保持當前的情況,因為在我的應用程式中而不是在資料庫中處理它們可能更有效?
uj5u.com熱心網友回復:
我可能遺漏了一些東西,但似乎所有表之間的簡單連接都可以實作這一點。
像這樣的東西:
select sc.class_id, c.name, sc.weight, sc.choice, t.teacher_desc
from student_choice sc, class c, teacher t
where sc.class_id = c.id
and sc.class_id = t.class_id and sc.choice = t.choice
and sc.student_id = {YOUR_STUDENT_ID}
或者,如果您更喜歡inner join語法:
select sc.class_id, c.name, sc.weight, sc.choice, t.teacher_desc
from student_choice sc
inner join class c on sc.class_id = c.id
inner join teacher t on sc.class_id = t.class_id and sc.choice = t.choice
where sc.student_id = {YOUR_STUDENT_ID}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457825.html
標籤:sql
