成都网站内容策划,广西seo公司,东莞专业做网站建设服务,企业所得税减免优惠政策最近遇到一个需求 #xff0c;需要对一个报表的多个字段进行多字段复杂条件排序 排序字段为NULL时
Mysql对于排序字段为NULL时#xff0c;有自身默认的排序规则#xff0c;默认是认为null 值 是无穷小
ELECT id,script_id,last_modified,live_count,next_show
FROM virtua… 最近遇到一个需求 需要对一个报表的多个字段进行多字段复杂条件排序 排序字段为NULL时
Mysql对于排序字段为NULL时有自身默认的排序规则默认是认为null 值 是无穷小
ELECT id,script_id,last_modified,live_count,next_show
FROM virtual_live_script
where 1 1and creator is null
ORDER BYlive_count desc,next_show asc,last_modified desc;
可以看到 next_show 为空的字段 的确按照 升序 是最小的 如果想让 next_show 为 null的记录排在最后 应该怎么处理呢可以在引入一个新的字段 比如sort 字段排序的时候 对这个新的字段也排序就可以实现上述逻辑同样的思路 还可以对null 值字段进行特殊处理
SELECT id,script_id,last_modified,live_count,next_show,next_show is null as sort
FROM virtual_live_script
where 1 1and creator is nullORDER BY live_count desc,sort asc,next_show asc,last_modified desc;还有一种不加辅助字段的方法利用IFNULL 函数这里给为空时间指定一个值只不过要在业务代码中要去除2030-01-01 00:00:00 这个有点侵入性
SELECT id,script_id,last_modified,live_count,ifnull(next_show,2030-01-01 00:00:00) as tmp
FROM virtual_live_script
where 1 1and creator is nullORDER BY live_count desc,tmp asc,last_modified desc;多条件复杂排序
对于多条件的复杂排序可以使用case … when语句类似如下思路 SELECT id,script_id,script_name,cover_url,last_modified,live_count,pre_count,end_count,status,next_show
FROM virtual_live_script
where 1 1and creator :creator
order by live_count desc,CASEWHEN live_count 0 AND next_show IS NULL THEN -1WHEN live_count 0 AND pre_count 0 THEN 0ELSE 0END desc,next_show asc,last_modified desc;参考
Mysql排序字段为NULL如何排序 sort-by-start-date-desc-if-end-date-is-null-if-not-sort-by-end-date