如何为select语句设置默认值

时间:2018-11-27 07:19:37

标签: mysql

我有这个要求,但是默认值显示为空。

SELECT c.course_id, 
       cast(AVG(fb.course_rate) as decimal(2,1)), 
       cast(AVG(fb.difficult) as decimal(2,1)),
       course_code,
       date, 
       course_col, 
       course_level, 
       course_name 
FROM course AS c 
LEFT JOIN course_feedback AS fb
  ON fb.course_id = c.course_id 
Where course_code LIKE '%$course_code%'  
GROUP BY c.course_id" 

我需要为列设置默认值0

cast(AVG(fb.course_rate) as decimal(2,1))

1 个答案:

答案 0 :(得分:0)

似乎NULL列中有fb.course_rate个值。您可以使用COALESCE()函数来处理它们

SELECT c.course_id, 
       cast(COALESCE(AVG(fb.course_rate), 0) as decimal(2,1)), 
       cast(AVG(fb.difficult) as decimal(2,1)),
       course_code,
       date, 
       course_col, 
       course_level, 
       course_name 
FROM course AS c 
LEFT JOIN course_feedback AS fb
  ON fb.course_id = c.course_id 
Where course_code LIKE '%$course_code%'  
GROUP BY c.course_id"