嗨,我有一張course桌子
course_id name type
1 Arthematic Maths
2 Geometry Maths
3 Chemistry Science
4 Biological Science
5 Hisotry Social
6 Independence Social
更多這樣的記錄和student表
student_id name
101 David
102 Tony
103 Skye
104 Nicole
105 Ossof
和一個student_course多對多連接表
id student_id course_id
1 102 2
2 102 3
3 101 1
4 101 2
5 101 3
6 103 2
7 103 5
8 104 3
9 105 1
10 104 5
我正在嘗試查找所有具有給定課程 ID 的數學和科學課程型別的學生。意味著我需要為給定的課程 ID 輸入找到至少一門數學型別課程和至少一門科學課程型別的學生
select sc.student_id from student_course sc left join course c on sc.course_id = c.id
where c.type = 'Maths' OR c.type = 'Science' and c.id IN (1,3,5)
group by sc.student_id having count(sc.student_id) >= 2
uj5u.com熱心網友回復:
在這種情況下,最好使用in運算子來避免與括號相關的邏輯錯誤,也應該使用countwithdistinct來避免計算相同的型別。
select sc.student_id
from student_course sc inner Join course c on sc.course_id = c.id
where c.type In ('Maths','Science') and c.id in (1,3,5)
group by sc.student_id
having Count(distinct c.type) = 2
db<>提琴手
結果:
| 學生卡 |
|---|
| 101 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418520.html
標籤:
