数字排序mysql,MySQL查询数字排序

I have the following query:

$result = $mysqli->query('SELECT DISTINCT SKU_SIZE_PART1

FROM SKU_DATA

WHERE SKU_BRANDNAME = "'.$brand.'"

ORDER BY SKU_SIZE_PART1 DESC');

while( $row = $result->fetch_assoc()){

$sku_size1 = $row['SKU_SIZE_PART1'];

echo $sku_size1;

}

Basically what is happening is.. the order is all messed up. This is what comes up:

9.50, 8.75, 8.00, 7.50, 7.00, 37, 35, 33, 325, 32, 315, 31, 305, 30, 295

325 should come up first, then 315 then so on.

What can I do to make this happen?

解决方案

You need to cast sku_size_part1 into a float.

This will slow your query down, but it will work:

$brand = mysqli_real_escape_string($brand);

$result = $mysqli->query("SELECT DISTINCT sku_size_part1

FROM sku_data

WHERE sku_brandname = '$brand'

ORDER BY CAST(sku_size_part1 AS FLOAT) DESC");

This will slow the query down, because MySQL will not be able to use an index to do the sorting, using a function prevents that.

A better solution (if possible) would be to redefine sku-size_part1 as a decimal(10,2).

-- Make a backup first --

ALTER TABLE sku_data CHANGE sku_size_part1 DECIMAL(10,2);

(Make sure the first parameter (10) and the second parameter (2) are large enough to hold all possible values.)

See: http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值