MYSQL - 使用条件顺序bys

时间:2010-08-02 06:00:42

标签: sql mysql

我在使用条件ORDER BY时遇到问题。我想做这样的事情

SELECT promotion_expires,created_at
FROM `notes` ORDER BY
CASE WHEN (promotion_expires > NOW()) THEN
    'promotion_expires DESC,created_at DESC'
ELSE
    'created_at DESC'
END;

即。结果应该首先有行,其中promotion_expires> NOW()按'promotion_expires,created_at'排序,后跟'created_at'排序的其他行

例如 -


+---------------------+---------------------+
| promotion_expires   | created_at          |
+---------------------+---------------------+
| 2010-08-01 02:39:53 | 2010-07-24 02:39:54 |
| NULL                | 2010-07-23 02:39:54 |
| NULL                | 2010-07-25 02:39:54 |
| 2010-08-08 02:39:54 | 2010-07-27 02:39:54 |
| 2010-08-06 01:39:54 | 2010-07-27 01:39:54 |
| 2010-08-06 01:39:54 | 2010-07-27 02:39:54 |
+---------------------+---------------------+

应该像

一样订购


+---------------------+---------------------+
| promotion_expires   | created_at          |
+---------------------+---------------------+
| 2010-08-08 02:39:54 | 2010-07-27 02:39:54 |
| 2010-08-06 01:39:54 | 2010-07-27 02:39:54 |
| 2010-08-06 01:39:54 | 2010-07-27 01:39:54 |
| NULL                | 2010-07-25 02:39:54 |
| 2010-08-01 02:39:53 | 2010-07-24 02:39:54 |
| NULL                | 2010-07-23 02:39:54 |
+---------------------+---------------------+

我想这样做只是使用条件顺序bys而不是联合

由于

3 个答案:

答案 0 :(得分:3)

需要添加括号。

语法如:

select ... from tablename order by
(case 
when "val1" then field1
when "val2" then field2
else field3 end)

请参阅本页的评论

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

在你的情况下

SELECT promotion_expires,created_at
FROM `notes` ORDER BY    
(CASE WHEN (promotion_expires > NOW()) THEN
        'promotion_expires DESC,created_at DESC'
    ELSE
        'created_at DESC'
    END);

答案 1 :(得分:3)

试试这样 ORDER BY IF(promotion_expires > NOW(),promotion_expires,1) DESC, created_at DESC

答案 2 :(得分:0)

尝试:

   SELECT promotion_expires, created_at FROM    
   ( SELECT promotion_expires,
           created_at ,
           CASE WHEN (promotion_expires > NOW()) 
                THEN promotion_expires 
           ELSE created_at END AS ORDER_DT1,
           CASE WHEN (promotion_expires > NOW()) 
                THEN created_at
           ELSE promotion_expires END AS ORDER_DT2

      FROM notes 
      ORDER BY ORDER_DT1 DESC, ORDER_DT2 DESC
    );