MySQL Query Sorting with Numbers
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;
}
Basicall开发者_开发百科y 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
精彩评论