两个特定记录和数据之间的MYSQL命令为NULL

时间:2015-06-06 12:44:01

标签: mysql sql mysqli phpmyadmin

有没有办法在特定记录中将MYSQL使用的默认顺序设置为NULL。

我的专栏:

  • id:id
  • state:'下载','错误','完成','失败'
  • try:尝试下载文件的次数。

结果中的顺序:

  • 下载
  • 错误:如果尝试介于0到20之间
  • NULL
  • 错误:尝试大于20
  • 失败

我的表:

id       state          try
----------------------------
1        NULL            0
2        error           25
3        downloading     1
4        NULL            0
5        finish          2
6        error           3
7        NULL            0
8        downloading     5
9        fail            51
10       error           3
11       error           21
12       error           8
13       finish          10
14       downloading     6
15       error           17

运行查询后的结果:

id       state         try
-------------------------------
3        downloading     1
8        downloading     5
14       downloading     6
10       error           3
12       error           8
15       error           17
6        error           3
1        NULL            0
4        NULL            0
7        NULL            0
11       error           21
2        error           25
9        fail            51

我的查询不起作用:

 SELECT * FROM `report_table`
            WHERE state IN ('downloading', 'error','fail')
                OR state IS NULL
            ORDER BY
                CASE
                    WHEN state = 'downloading' THEN 1
                    WHEN state IS NULL THEN 2
                    WHEN state = 'error' THEN 3
                    WHEN state = 'fail' THEN 4
                    ELSE 6
                END , state ASC , try ASC

2 个答案:

答案 0 :(得分:0)

您只需要正确的ORDER BY

ORDER BY (CASE WHEN state = 'downloading' THEN 1
               WHEN state = 'error' and try between 0 and 20
               WHEN state IS NULL THEN 3
               WHEN state = 'error' THEN 4
               WHEN state = 'fail' THEN 5
               ELSE 6
          END), state ASC , try ASC

如果state没有其他值,则state ASC中不需要order by

答案 1 :(得分:0)

SELECT * FROM `report_table`
WHERE state IN ('downloading', 'error','fail') OR state IS NULL
ORDER BY
    CASE WHEN state = 'downloading' THEN 1
         WHEN state = 'error' AND try<=20 THEN 2
         WHEN state IS NULL THEN 3
         WHEN state = 'error' AND try>20 THEN 4
         WHEN state = 'fail' THEN 5
         ELSE 6
     END , state ASC , try ASC

结果:

id  state       try
3   downloading 1
8   downloading 5
14  downloading 6
6   error       3
10  error       3
12  error       8
15  error       17
7   (null)      0
4   (null)      0
1   (null)      0
11  error       21
2   error       25
9   fail        51

SQL Fiddle中的示例结果。