结果列表顶部的指定记录

时间:2012-03-06 10:15:10

标签: sql ansi-sql

任务:在结果列表顶部选择指定记录

我丑陋的变种:

(select * from mytable where id = 42)
union all
(select * from mytable where id != 42 order by id)
ansi mysql以外,{{1}}的查询变体对我来说也很有趣

2 个答案:

答案 0 :(得分:3)

ANSI和供应商SQL解决方案之间没有区别

select *
from mytable 
order by
    CASE WHEN id = 42 THEN 0 ELSE 1 END, id

注意:对于没有ORDER BY子句的表或SELECT,有保证或隐含的顺序

答案 1 :(得分:1)

假设id始终为正,请尝试:

select *
from mytable 
order by CASE WHEN id = 42 THEN 0 ELSE id END