混合字符串和数值排序

时间:2014-10-06 15:47:11

标签: php mysql

$query = "SELECT * FROM price   
ORDER BY CAST(price AS DECIMAL(10,2))  
DESC LIMIT $from, $max_results";

此查询显示的结果

Example
________________________
Product      | Price
________________________
Shoes         | 94,200 
________________________
Shirts        |66,900
________________________
Socks         |59,900
________________________
T-shirt       |49,700
________________________
Shirt Cloth   |Coming Soon
________________________
Shirt pant    |Coming Soon
________________________
Shirt jacket  |Coming Soon
________________________

我想要那样

Example
________________________
Product      | Price
________________________
Shirt Cloth   |Coming Soon
________________________
Shirt pant    |Coming Soon
________________________
Shirt jacket  |Coming Soon
________________________
Shoes         | 94,200 
________________________
Shirts        |66,900
________________________
Socks         |59,900
________________________
T-shirt       |49,700
________________________

我该怎么做才能帮我解决这个问题 感谢

2 个答案:

答案 0 :(得分:4)

您可以通过

执行条件订单
ORDER BY
  CASE price
    WHEN "Coming Soon" THEN 1
    ELSE 2
  END ASC,
CAST(REPLACE(price, ',', '') AS decimal(10,2)) DESC

这样的美妙之处在于你可以拥有多种条件......所以我们说除了即将推出之外你还有另外一个价值,还有一个数字......比如'Out Of Stock'你可以很容易地将它纳入你的陈述中

答案 1 :(得分:3)

order by可以有任意表达式:

ORDER BY (price = 'Coming Soon') DESC, CAST(price AS decimal(10,2))

如果价格为Coming Soon,则price = 'Coming Soon'将评估为布尔值TRUE。如果它不相等,那么它的布尔值为false。使用DESC排序,首先是真值,然后是假值。在这些真/假块中,CAST(...)将进一步对实际价格进行排序。