Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtraction returning null value mysql

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

I am trying to update tot_cred in student by subtracting the credit value of any class the student has failed, grade in takes relation = 'F', or is currently taking, grade in takes relation IS NULL.

The query above however sets tot_cred to NULL for any of the students who meet this criteria and I cannot figure out why.

I apologize if this has been asked before, I tried to search for something relevant but couldn't find many issues related to subtraction. I am new to stackoverflow. Thank you all for your help.

like image 287
Austin Johnston Avatar asked Feb 17 '23 08:02

Austin Johnston


2 Answers

add COALESCE on c.credits

set s.tot_cred = s.tot_cred - COALESCE(c.credits,0)
like image 89
John Woo Avatar answered Feb 28 '23 03:02

John Woo


You can use COALESCE like @JW answer, or use 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
like image 40
Iswanto San Avatar answered Feb 28 '23 04:02

Iswanto San