我在表格中有以下数据
pk | i | val
------------
1 | 0 | hi
2 | 3 | good bye
3 | 4 | good day
5 | 6 | howdy
如果我select * from mytable ORDER BY val
,我会收到订单2,3,1,5。
但是如果我想在其他正常排序的行之前给两个特定的行赋予“首选项”呢?让我们说val = hi,再见。
换句话说,我如何编写SQL查询以便能够返回1,5,2,3?
答案 0 :(得分:2)
select *
from table1
order by case when val in ('hi', 'howdy') then 0 else 1 end, val
<强> sql fiddle demo 强>
或
select *
from table1
order by
case val
when 'howdy' then 0
when 'hi' then 1
else 2
end, val
或(更容易添加新变量)
select *
from table1
order by
case val
when 'howdy' then 2
when 'hi' then 1
else 0
end desc, val