假如统计每科的总分数,出现了空值怎么办
用coalesce(sum(degreee),0)
,例子如下:
课程表
mysql> select * from t_course;
+-------+-----------------+-----+
| cno | cname | tno |
+-------+-----------------+-----+
| 3-105 | 计算机导论 | 825 |
| 3-245 | 操作系统 | 804 |
| 6-166 | 数据电路 | 856 |
| 9-888 | 高等数学 | 100 |
+-------+-----------------+-----+
成绩表
mysql> select * from t_score;
+-----+-------+--------+
| sno | cno | degree |
+-----+-------+--------+
| 103 | 3-245 | 86 |
| 105 | 3-245 | 75 |
| 109 | 3-245 | 68 |
| 103 | 3-105 | 92 |
| 105 | 3-105 | 88 |
| 109 | 3-105 | 76 |
| 101 | 3-105 | 64 |
| 107 | 3-105 | 91 |
| 108 | 3-105 | 78 |
| 101 | 6-166 | 85 |
| 107 | 6-106 | 79 |
| 108 | 6-166 | 81 |
+-----+-------+--------+
统计每个学科的总分数
select cname,coalesce(sum(b.degree),0) from t_course a left join t_score b on a.cno=b.cno group by b.cno;
mysql> select cname,coalesce(sum(b.degree),0) from t_course a left join t_score b on a.cno=b.cno group by b.cno;
+-----------------+---------------------------+
| cname | coalesce(sum(b.degree),0) |
+-----------------+---------------------------+
| 高等数学 | 0 |
| 计算机导论 | 489 |
| 操作系统 | 229 |
| 数据电路 | 166 |
+-----------------+---------------------------+
4 rows in set (0.06 sec)