实战
测试数据库 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, 0) 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
ISNULL
用于检查表达式是否为 NULL 的函数。
语法如下:
ISNULL ( expression, value_if_null )
expression
: 要检查是否为 NULL 的表达式。value_if_null
: 如果expression
为 NULL,则返回的值。如果expression
不为 NULL,则返回expression
的值。
例如,如果你有一个列 score
,你想要在查询中使用 ISNULL
将 NULL 值替换为一个特定的值,可以这样写:
SELECT ISNULL(score, ‘N/A’) AS new_a FROM your_table;
COALESCE
用于返回参数列表中第一个非 NULL 表达式的函数。如果所有参数都为 NULL,COALESCE
将返回 NULL。
语法如下:
COALESCE(expression1, expression2, …, expressionN)
expression1
,expression2
, …,expressionN
: 要评估的表达式列表。
COALESCE
从左到右评估参数,返回第一个非 NULL 的表达式的值。
如果所有参数都是 NULL,则 COALESCE
返回 NULL。
这在处理需要从一系列可能为 NULL 的表达式中选择第一个非 NULL 值的情况时非常有用。