按ASC排序,底部为空

时间:2011-05-13 14:05:43

标签: mysql sql sql-order-by

我正在编写一个将学校表连接到地区表的SQL查询。简单的一对多关系,每所学校都隶属于一个学区。我的查询如下:

SELECT 
    schools.id AS schoolid,
    schools.name AS school, 
    districts.id AS districtid, 
    districts.name AS district
FROM sms_schools AS schools
    LEFT JOIN sms_districts AS districts ON schools.districtid = districts.id
WHERE 1 = 1
ORDER BY districts.name, schools.name

我做左联的原因是因为不是每个学校都附属于一个学区。例如,一所学校可能是家庭教育,可能包含所有在家接受教育的学生。那不会是在一个地区。

所以我想做的是使用ORDER BY来按地区名称和学校名称进行排序。唯一的问题是我希望null区位于底部,这样我就可以在输出的末尾使用一个名为“Other”的组。

是否可以通过在输出结尾处以空值递增来进行排序?

4 个答案:

答案 0 :(得分:38)

在询问问题后仅1分钟我找到了答案。在order by子句中,用例使空值具有比其他任何值更高的值:

 ORDER BY (CASE WHEN districts.id IS NULL then 1 ELSE 0 END),districts.name, schools.name;

答案 1 :(得分:24)

您可以使用ISNULL()功能。

来自MySQL manual

  

<强> ISNULL(expr

     

如果exprNULL,则ISNULL()会返回1,否则会返回0

例如

ORDER BY ISNULL(districts.name), districts.name, schools.name

我喜欢使用它而不是MySQL的CASE选项。请注意,它是不可移植,因为ISNULL()不是标准SQL,并且在其他版本的SQL中功能不同。

答案 2 :(得分:5)

默认情况下,Null位于顶部,但您可以使用IsNull指定默认值,这会将其置于您需要的位置......


SELECT schools.id AS schoolid,schools.name AS school, districts.id AS districtid, districts.name AS district FROM sms_schools AS schools LEFT JOIN sms_districts AS districts ON schools.districtid = districts.id WHERE 1 = 1 
ORDER BY isnull(districts.name,'1'), schools.name 

答案 3 :(得分:2)

SELECT
 schools.id AS schoolid,
 schools.name AS school,
 districts.id AS districtid,
 districts.name AS district,
 if(schools.districtid IS NULL,1,0) as sort 
FROM sms_schools AS schools
LEFT JOIN sms_districts AS districts 
 ON schools.districtid = districts.id
WHERE 1 = 1
ORDER BY sort, districts.name, schools.name

将更多排序规则放入'new'colunm并使用任何数字 隐藏代码中的字段,测试是否可以对if目录进行排序(按if ...排序)

祝你好运