2013-03-04 131 views
3
UPDATE student as s 
LEFT JOIN takes as t 
    ON s.ID = t.ID 
LEFT JOIN course as c 
    ON t.course_id = c.course_id 
SET s.tot_cred = s.tot_cred - c.credits 
WHERE t.grade = 'F' OR t.grade IS NULL 

我試圖通過減去學生失敗的任何班級的學分值來更新學生的tot_cred,或者正在考慮在等級中的等級,一片空白。減法返回空值mysql

但是,對於符合此條件的任何學生,上面的查詢將tot_cred設置爲NULL,我無法弄清楚原因。

我很抱歉如果之前詢問過,我試圖尋找相關的東西,但找不到與減法有關的許多問題。我是新的stackoverflow。感謝大家的幫助。

回答

2

c.credits

set s.tot_cred = s.tot_cred - COALESCE(c.credits,0) 
+0

它爲空值和F級的,還有3 null發生。我不相信這是導致這個問題的聯盟。我會看看我的查詢並試圖弄清楚。感謝您對此問題的幫助! – 2013-03-04 06:36:45

1

添加COALESCE可以使用COALESCE像@JW答案,或使用IFNULL

UPDATE student as s 
LEFT JOIN takes as t 
    ON s.ID = t.ID 
LEFT JOIN course as c 
    ON t.course_id = c.course_id 
SET s.tot_cred = s.tot_cred - IFNULL(c.credits, 0) 
WHERE t.grade = 'F' OR t.grade IS NULL