按顺序由ASC在底部的空值
我正在写一个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按照地区名称和学校名称进行sorting。 唯一的问题是,我希望null区位于底部,这样我就可以在输出结尾使用一个名为“Other”的组。
在输出结束时,是否可以用空值升序来进行sorting?
提问后只有1分钟,我find了答案。 在order by clause用例中,使null值比其他任何值都有更高的值:
ORDER BY (CASE WHEN districts.id IS NULL then 1 ELSE 0 END),districts.name, schools.name;
你可以使用ISNULL()
函数。
从MySQL手册 :
ISNULL(
expr
)如果
expr
为NULL
,则ISNULL()
返回1
,否则返回0
。
例如 :
ORDER BY ISNULL(districts.name), districts.name, schools.name
我喜欢用这个而不是MySQL的CASE
选项。 请注意,它不可移植,因为ISNULL()
不是标准的SQL,在其他版本的SQL中function不同。
默认情况下会在顶部出现空值,但是您可以使用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
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
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
把任何更多的sorting规则insite“新”colunm,并使用任何数字隐藏在您的代码中的字段,testing是否属于如果直接sorting(if by …)
祝你好运