很多开发业务中都会碰到这样的需求,将自己的一些信息,优先排到前面,一般的SQL会怎么写?以Message这张表为例,要求查出当前登录用户的message信息优先排在前面,如果可以获取到当前的登录用户的userId为1222222,下面提供两种方法:
1.
select * from Message order by case userId when 1222222 then 1 else 0 end desc;
(case userId when 1222222 then 1 else 0 end的语法的意思是当userId 是1222222时候userId虚拟化为1,其他的虚拟化为0,然后按照1和0进行排序,如果下面是desc 则userId为1222222的都排在前面,如果没有desc,则默认是ASC)
2.第二种方法是用union关键字,类似的如下
select ad_id as id from info_ad where end_time=’没有过期’
union all
select t.ad_id from
(select ad_id from info_ad where end_time=’过期’ order by rand()) t limit 30;
如果加多个条件进行排序会怎样呢?
SELECT * FROM ceres_message ORDER BY (CASE content_type WHEN ‘court_make’ THEN 2 when ‘wait_trial_inti’ then 1 ELSE 0 end) DESC,(CASE is_deleted WHEN ‘y’ then 1 else 0 END )DESC;
(这句sQL的意思是先按照content_type这个字段进行排序content_type为court_make虚拟化为2,content_type为wait_trial_inti虚拟化为1,其他的虚拟化为0,然后按照从2到0进行排序,is_deleted字段同理有兴趣的同学可以试试看效果)