max()函数没有获得最大值

时间:2015-10-25 12:41:58

标签: php mysql

我有一张桌子"订单"在mysql数据库中,它包含列" order_number" 。并且因为每个订单都有几行(取决于eshop订单的大小),列" order_number"看起来像这样:

1
1
1
2
2
2
2
2
3
3
3个

....等...目前大约有1000个订单,这意味着表中有数千行。我想要做的只是检索最高订单号...听起来很容易:

$ result = mysql_query(" SELECT max(order_number)as max FROM orders");
$ lastordernumber = mysql_fetch_array($ result);
echo $ lastordernumber [" max"];

...这将返回" 99" ,而目前最高订单数接近1000。任何想法?

谢谢!

1 个答案:

答案 0 :(得分:1)

当“order_number”是一个字符串时会发生这种情况。您应该将其存储为数值,如果这是您想要的那样。但是,出于此查询的目的,您可以将其视为数字:

select max(order_number + 0) as max
from orders;

或者,您可以将查询编写为:

select order_number
from orders
order by len(order_number) desc, order_number desc
limit 1;