order by case when 使用方法

假设现在项目(project)状态分为以下几种:
/**

  • 草稿
    /
    DRAFT(1),
    /
    *
  • 已发布
    /
    RELEASED(2),
    /
    *
  • 已下架
    /
    REMOVED(3),
    /
    *
  • 已删除
    */
    DELETED(4);

现在想要展示已经发布的项目展示在最上面,然后是草稿、已下架、已删除状态的项目

select 
	id, name, subject_type_required, created_time
from project 
order by case status 
when 2 then 1
when 1 then 2
when 3 then 3
when 4 then 4
end asc,
created_time desc;

order by 后面用case when 并不等于 order by 数字

示例1:
SELECT last_name, salary , hire_date
FROM EMPLOYEES
ORDER BY salary DESC;
示例2:
SELECT last_name, salary , hire_date
FROM EMPLOYEES
ORDER BY 2 DESC;
以上两个示例结果相同。
因为ORDER BY salary DESC==ORDER BY 2 DESC
salary是第二个元素,所以可以使用2来代替。
但是数字不可以使用0,也不可以超出查询的列。
例如:select * from employers
order by x;
如果employers表有九个字段,那个X的范围就是1—9
不能是0,也不能是10.

发布了36 篇原创文章 · 获赞 4 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/weixin_41205148/article/details/100125012
今日推荐