MYSQL - ORDER BY子句

时间:2013-10-30 08:51:49

标签: mysql sql-order-by

我有一些像这样的记录

id  name    sequence
------------------------
1   steve   3
2   lee     2
3   lisa    1
4   john    0
5   smith   0

我想显示如下的记录

id  name
------------
1   lisa
2   lee
3   steve
4   john
5   smith

当我使用order by子句时,它显示为

name
----
john
smith
lisa
lee
steve

查询

SELECT name from tbl1 where 1 ORDER BY sequence ASC

2 个答案:

答案 0 :(得分:5)

SELECT name
FROM tbl1 
ORDER BY sequence = 0,
         sequence ASC

SELECT name
FROM tbl1 
ORDER BY case when sequence <> 0 then 1 else 2 end,
         sequence ASC

答案 1 :(得分:0)

您可以在ORDER BY子句

中使用if if条件查询
SELECT
  name
from tbl1
ORDER BY IF(sequence = 0,name,sequence) ASC

Fiddle

输出

|  NAME |
|-------|
|  lisa |
|   lee |
| steve |
|  john |
| smith |