排序时出现字段值为空的时候,会出现正序空值排在最前面,倒序空值排在最后面。
1.png
对该组数据根据birthday进行排序
SELECT * FROM Student order by birthday
image.png
空值的数据排在最前面了,但是需求有时候需要将空值排在最后,但是其他数据需要正序排序。
SELECT * FROM Student order by case when birthday is null then 1 else 0 end,birthday
达到预期的效果,空值放到最后,其他值按照正序排序。
image.png
SELECT * FROM Student order by case when birthday is null then 0 else 1 end,birthday
0和1置换后,出现如下结果。
image.png
case的语句格式是 case 。。。。。。。。。。end
它结构就是这样的,解释一下,
case ------------假设
when birthday is null then 1 -----------birthday是空,则返回值1
else 0 -----------非空,则返回值0
end