日期:2014-05-16  浏览次数:20675 次

mysql中null值的排序问题分析
如下表t_user:
nameage
zhangsan1
lisiNULL
wangwu2


执行一下sql:
select * from t_user order by age;

nameage
lisiNULL
zhangsan1
wangwu2


实际上我们是想将没有填写age的记录放在最后,我们可以
select * from t_user order by age is null, age;

nameage
zhangsan1
wangwu2
lisiNULL


为什么会这样?可以这样来理解:
select * from t_user order by age is null, age;

等价于:
select * from (select name, age, (age is null) as isnull from t_user) as foo order by isnull, age;

看出来了吗?