使用IF语句对ASC和DESC进行排序取决于另一个列值

时间:2017-01-25 10:36:07

标签: mysql sql laravel

我在SQL中有点新,需要按日期对列进行排序。

Compare how it should to be and how it seems now

尝试了这段代码,但没有工作:

SELECT   * 
FROM     `onetime_contest`  
ORDER BY `onetime_contest`.`status` ASC,
      IF (@status = 'live', `onetime_contest`.`valid_till`, '') ASC,
      IF (@status = 'waiting', `onetime_contest`.`valid_till`, '') ASC,
      IF (@status = 'completed', `onetime_contest`.`valid_till`, '') DESC,
      IF (@status = 'not_actual', `onetime_contest`.`valid_till`,'') DESC

1 个答案:

答案 0 :(得分:0)

说实话,我不知道为什么这样可行,除了它似乎说服mysql遵守子查询中的order by子句。

drop table if exists `onetime_contest`;
create table `onetime_contest`(id int, status varchar(20),valid_till date);
insert into `onetime_contest` values
(1,'live','2017-01-01'),
(2,'waiting','2017-01-01'),
(3,'completed','2017-01-01'),
(4,'not-actual','2017-01-01'),

(5,'live','2017-06-01'),
(6,'waiting','2017-06-01'),
(7,'completed','2017-06-01'),
(8,'not-actual','2017-06-01');

ariaDB [sandbox]> select * from
    -> (SELECT 1 sortorder,id,status,valid_till
    -> #if(ot.valid_till <> @p,@rn:=@rn -  1 , @rn:=@rn) rn,
    -> #@p:=ot.valid_till
    -> FROM  (select @rn:=999999,@p:='1957-01-01') b,`onetime_contest` ot
    -> where status = 'live'
    -> order by valid_till asc
    -> ) a
    -> union
    -> select * from
    -> (SELECT 2 sortorder,id,status,valid_till
    -> #if(ot.valid_till <> @p1,@rn1:=@rn1 +  1 , @rn1:=@rn1) rn,
    -> #@p1:=ot.valid_till
    -> FROM  (select @rn1:=0,@p1:='1957-01-01') b,`onetime_contest` ot
    -> where status = 'not-actual'
    -> order by valid_till desc
    -> ) b
    -> union
    -> select * from
    -> (SELECT 3 sortorder,id,status,valid_till
    -> #if(ot.valid_till <> @p2,@rn2:=@rn2 -  1 , @rn2:=@rn2) rn,
    -> #@p2:=ot.valid_till
    -> FROM  (select @rn2:=999999,@p2:='1957-01-01') b,`onetime_contest` ot
    -> where status = 'completed'
    -> order by valid_till desc
    -> ) c
    -> ;;
+-----------+------+------------+------------+
| sortorder | id   | status     | valid_till |
+-----------+------+------------+------------+
|         1 |    1 | live       | 2017-01-01 |
|         1 |    5 | live       | 2017-06-01 |
|         2 |    8 | not-actual | 2017-06-01 |
|         2 |    4 | not-actual | 2017-01-01 |
|         3 |    7 | completed  | 2017-06-01 |
|         3 |    3 | completed  | 2017-01-01 |
+-----------+------+------------+------------+
6 rows in set (0.00 sec)