实战
测试数据库 test:
--------------------- | id | name | score | --------------------- | 1 | lily | 80 | --------------------- | 3 | jane | 70 | --------------------- | 4 | tom | NULL | --------------------- | 8 | jack | 98 | ---------------------
需求:
根据score,从高到低排序:
方法1:(有错误)
select id ,name,score from test order by score desc
结果集:
--------------------- | id | name | score | --------------------- | 4 | tom | NULL | --------------------- | 8 | jack | 98 | --------------------- | 1 | lily | 80 | --------------------- | 3 | jane | 70 | ---------------------
从结果可以看出NULL的字段排在了最前边,现在需要把它排到最后。
方法2:
使用 ISNULL:
select id ,name,score from test order by ISNULL(score) asc, score desc
结果集:
--------------------- | id | name | score | --------------------- | 8 | jack | 98 | --------------------- | 1 | lily | 80 | --------------------- | 3 | jane | 70 | --------------------- | 4 | tom | NULL | ---------------------
方法3:
使用 COALESCE:
select id ,name,score from test order by COALESCE(score, 0) desc
方法4:
使用 CASE WHEN :
SELECT id ,name,score FROM test ORDER BY CASE WHEN scoreIS NULL THEN 1 ELSE 0 END ASC, scoreDESC