2017-01-25 5 views
-3

私は少し新しくSQLで、日付で列を並べ替える必要があります。私は、これはサブクエリにORDER BY句を称えるためにMySQLを説得すると思われることを除いて働く理由はわかりませんIF文を使用したASCとDESCの並べ替えは、別の列の値に依存します。

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 
+0

Not working means ?? –

+0

誤った順序でソートする:)私はコアが間違って書かれていると思います。 – Brian

答えて

0

を正直に言うと:動作しない、このコードを試しました

Compare how it should to be and how it seems now

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:[email protected] - 1 , @rn:[email protected]) 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:[email protected] + 1 , @rn1:[email protected]) 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:[email protected] - 1 , @rn2:[email protected]) 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) 
関連する問題