2014-12-22 27 views
0

我有ER圖如下圖所示SQLite的「出現的課程量爲每一個學生他是否出席與否」 SQL查詢

ER Diagram

每一個學生,我希望出現的所有課程,加數。 於是我就用查詢

select studentId,course.courseCode 
from student natural left outer join attends 
natural left outer join course 

這使我在正確的方式,所有結果

enter image description here

現在我希望出現的,一個學生參加 課程總量和我使用此查詢

select studentId, 
    (select count(attends.courseCode) 
    from attends natural left outer join student 
)as 'amount' 
from student 

,但我有這個結果

enter image description here

我該如何顯示每個學生的課程真實數量,無論他是否參加?也就是說,對於studentId 6,7,8 0和studentId 17等2 預先感謝您

PS1:如果您想了解更多我的表,請讓我知道。

PS2:我是不知道的稱號。如果你發現另一個標題更適合的,請建議

回答

2

首先,不要使用natural join。它完全依賴於數據結構 - 如果發生變化,則查詢的語義也會發生變化。換句話說,你不能閱讀一個查詢並且真正理解它在做什麼。

然後,該查詢,首先使用cross join所有學生和課程的列表,然後將在考勤信息:

select s.studentId, c.courseCode, count(a.CourseCode) 
from student s cross join 
    course c left join 
    attends a 
    on s.studentId = a.studentId and s.courseCode = c.courseCode 
group by s.studentId, c.courseCode; 
+0

恐怕不給我我所期望的結果。 ..in我的例子,studentId 17名出席2個療程,並返回其參加一個 –

+0

和別的東西:我可以用左連接的天然istead加入?所以我的查詢可以是'select student.studentId,course.courseCode from student left join attends using(studentId) left join course using(courseCode)'? –

+0

好吧,我的錯誤我明白髮生了什麼事。謝謝! –

相關問題