简体   繁体   English

如何在结果中最后以0排序

[英]How to sort with 0 on the end in result

I have a list of products with prices. 我有价格清单。 Some products are prices only aviable on request. 有些产品的价格仅应要求提供。 This products are labeled with a price of 0 in the database. 该产品在数据库中标有价格0。
If I now make a request like: 如果我现在发出这样的请求:

$sql = "SELECT * FROM products WHERE ORDER BY Price ASC";

The Results are of course starts with a price of 0. 结果当然是从0开始的。
But I want all the 0 prices at the end of the results. 但是我希望所有0价格都在结果的结尾。
Is this possible with a SQL request or what is the best solution to re-sort in php? SQL请求是否有可能,或者在php中重新排序的最佳解决方案是什么?
Thx in advanced Thx高级
Bernd 贝恩德

You may sort using a CASE expression which places zero prices last: 您可以使用CASE表达式排序,最后将零价格放置:

SELECT *
FROM products
WHERE ...
ORDER BY
    CASE WHEN Price > 0 THEN 0 ELSE 1 END,
    Price;

In MySQL, the ORDER BY clause can be simplified: 在MySQL中,可以简化ORDER BY子句:

SELECT *
FROM products
WHERE ...
ORDER BY
    Price = 0,    -- false (0) for positive prices, true (1) for zero prices
    Price;

Yes you can by using bitwise negation to make 0 the maximum value for a bigint in the sort. 是的,您可以通过按位取反将0用作bigint的最大值。

SELECT *
FROM products
ORDER BY
    CASE WHEN Price = 0 THEN ~0 ELSE Price END ASC

您可以使用mysql FIELD函数以所需顺序检索数据

   SELECT * FROM products WHERE ORDER BY FIELD(Price,0) ASC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM