mysql的order by排序时,有null值怎么办?
数据举例:以下几种排序方式及结果:1.null强制放在最后select id,sort from fwzl_housewhere delFlag = 0 and id in (9807,9786,9638,9679)order by if(isnull(sort),1,0) , sort asc或select id,sort from fwzl_housewhere delFlag = 0 and
·
数据举例:
以下几种排序方式及结果:
1.null强制放在最后
select id,sort from fwzl_house
where delFlag = 0 and id in (9807,9786,9638,9679)
order by if(isnull(sort),1,0) , sort asc
或
select id,sort from fwzl_house
where delFlag = 0 and id in (9807,9786,9638,9679)
order by if(isnull(sort),0,1) desc , sort asc
结果如下:
2.将null强制放在最前
select id,sort from fwzl_house
where delFlag = 0 and id in (9807,9786,9638,9679)
order by if(isnull(sort),0,1) , sort asc
或
select id,sort from fwzl_house
where delFlag = 0 and id in (9807,9786,9638,9679)
order by if(isnull(sort),1,0) desc , sort asc
结果如下:
理解:
以if(isnull(字段名),0,1)为例,它的意思是将该字段值为null得到一个隐含的排序属性0,值为非null的得到一个隐含的排序属性1,
在排序的时候,先根据这一隐含属性进行升序排列,【因为if(isnull(字段名),0,1)相当于if(isnull(字段名),0,1) asc,省略了asc】,所以自然地,排序字段为null的那些行(隐含排序属性)会在最前。
对于将null强制放在最后同理。
更多推荐
已为社区贡献3条内容
所有评论(0)