我可以从给定的数字开始订购mysql吗?

时间:2009-11-16 15:36:14

标签: mysql

我在mysql表中有很多行。有一个order_id列。我想按两列排序,首先是order_id,然后是id(自动增量)。 问题是我为order_id输入了1,2,3,4,5 ......并为其他人留空。在我的示例中,我想首先显示具有数字1,2,3,4的行,但是它显示具有空白order_id的行,因为它小于1。 有没有办法在1开始订单?

示例:

id | order_id | name
1  | NULL     | test name 1
2  | 1        | test name 2
3  | NULL     | test name 3
4  | 2        | test name 4
5  | 3        | test name 5

我希望我的订单声明能够提供以下结果

test name 2
test name 4
test name 5
test name 1
test name 3

正如您从示例中看到的那样,我首先按“order_id”列从1开始订购

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

缺少的值是否用NULL表示?如果是这样,那么这样的事情应该可以解决问题:

SELECT *
FROM your_table
ORDER BY IF(order_id IS NULL, 1, 0), order_id, id

如果缺失的值不是NULL,那么您需要相应地更改IF子句。例如,如果缺少的字段实际上是空字符串,那么您可能会使用类似的东西:

SELECT *
FROM your_table
ORDER BY IF(order_id = '', 1, 0), order_id, id

答案 1 :(得分:1)

如果要省略order_id行,则只需添加where子句(where order_id is not null)。否则,请尝试在select中添加一列:

if(order_id IS NULL or order_id='', 1, 0)

然后首先在此列上对ASC进行排序,这将首先放入非空order_id

答案 2 :(得分:0)

您可以尝试使用ifnull函数增强查询。 所以你可以检查order_id是否为零,当它是自动增量订购时,否则按订单ID排序 请参阅mysql的文档: http://dev.mysql.com/doc/refman/4.1/en/control-flow-functions.html

相关问题