SELECT student.s_id,s_name,c_name,score FROM student INNER JOIN course LEFT JOIN score ON score.s_id = student.s_id AND score.c_id = course.c_id ORDER BY student.s_id
SELECT student.s_id,s_name,c_name,IF(score>=60,'及格','不及格') FROM student INNER JOIN course LEFT JOIN score ON score.s_id = student.s_id AND score.c_id = course.c_id ORDER BY student.s_id
SELECT student.s_id,s_name,c_name,IF(score is NULL,'缺考',score) FROM student INNER JOIN course LEFT JOIN score ON score.s_id = student.s_id AND score.c_id = course.c_id ORDER BY student.s_id
SELECT student.s_id,s_name,c_name,IFNULL(score,'缺考') FROM student INNER JOIN course LEFT JOIN score ON score.s_id = student.s_id AND score.c_id = course.c_id ORDER BY student.s_id
备注:
(1)IF 关键字的作用类似excel中的IF公式,它根据条件来输出字段的值
(2)Null与任何数字比较的结果,都是Null,而非True或False;而If关键字规定:如果比较结果为Null,则相当于结果为False,所以返回第二个值
(3)IF(字段X IS NULL, a, 字段X) 在 MySQL 中可以替换为:IFNULL(字段X, a)
SELECT student.s_id, s_name, c_name, (CASE WHEN score>85 THEN '优秀' WHEN score>=60 THEN '及格' WHEN score IS NULL THEN '缺考' ELSE '不及格' END) AS '评级' FROM student INNER JOIN course LEFT JOIN score ON score.s_id = student.s_id AND score.c_id = course.c_id ORDER BY student.s_id
CASE 语句分为简略格式与推荐使用的搜索模式,语法格式为:
CASE WHEN 情况1 THEN A WHEN 情况2 THEN B WHEN 情况3 THEN C ELSE D END