MySQL按字段顺序排列

时间:2012-02-07 16:50:40

标签: mysql sql-order-by

您好我试图使用他们的状态订购域数据。您可能知道,域名DOM_EXP或DOM_DAKT在域命中DOM_HELD之前适用因此我不关心这个状态之一在域名成为DOM_HELD之前是否具有域名

我如何订购这些数据?使用下面提供的select我只实现了DOM_DAKT正在使用DOM_EXP,但我希望它介于两者之间,由exp_date命令

SELECT domain_id, status, exp_date 
FROM domains 
ORDER BY 
field (status, 'DOM_DEL', 'DOM_HELD', 'DOM_EXP', 'DOM_DAKT'), 
exp_date ASC;

+-----------+----------+---------------------+
| domain_id | status   | exp_date            |
+-----------+----------+---------------------+
|         2 | DOM_DEL  | 2012-02-02 10:47:33 |
|         4 | DOM_HELD | 2012-02-02 10:47:38 |
|         5 | DOM_HELD | 2012-02-02 10:47:40 |
|         7 | DOM_HELD | 2012-02-02 10:47:44 |
|         1 | DOM_EXP  | 2012-02-02 10:47:27 |
|         3 | DOM_EXP  | 2012-02-02 10:47:35 |
|         6 | DOM_EXP  | 2012-02-02 10:47:42 |
|        54 | DOM_DAKT | 2012-02-02 10:47:39 |
+-----------+----------+---------------------+

结果必须像这样

+-----------+----------+---------------------+
| domain_id | status   | exp_date            |
+-----------+----------+---------------------+
|         2 | DOM_DEL  | 2012-02-02 10:47:33 |
|         4 | DOM_HELD | 2012-02-02 10:47:38 |
|         5 | DOM_HELD | 2012-02-02 10:47:40 |
|         7 | DOM_HELD | 2012-02-02 10:47:44 |
|         1 | DOM_EXP  | 2012-02-02 10:47:27 |
|         3 | DOM_EXP  | 2012-02-02 10:47:35 |
|        54 | DOM_DAKT | 2012-02-02 10:47:39 |
|         6 | DOM_EXP  | 2012-02-02 10:47:42 |
+-----------+----------+---------------------+

2 个答案:

答案 0 :(得分:2)

首先按“{1}}和DOM_EXP被视为等级的状态”排名“排序。然后在状态

的每个“等级”内按DOM_DAKT排序
EXP_DATE

SELECT domain_id, status, exp_date FROM domains ORDER BY CASE WHEN status = 'DOM_DEL' THEN 1 WHEN status = 'DOM_HELD' THEN 2 WHEN status = 'DOM_EXP' THEN 3 WHEN status = 'DOM_DAKT' THEN 3 -- EXP and DAKT are "of equal rank" END, EXP_DATE 表达式视为映射CASE => status

答案 1 :(得分:0)

只需从声明中删除DROP_EXPDOM_DAKT

SELECT domain_id, status, exp_date 
FROM domains 
ORDER BY 
field (status, 'DOM_DEL', 'DOM_HELD'), 
exp_date ASC;

假设DOM_EXPDOM_DAKT是唯一的其他状态。