按价格和折扣价格排序

时间:2015-11-12 08:56:51

标签: php mysql sql-order-by

我有下表:

product_id | price | discountPrice
    1      |  15   | 12
    2      |  13   | 0
    3      |  20   | 6

我想按折扣价对结果进行排序,但如果某个product_id的discountPrice等于0,则此product_id应按价格排序。

预期结果:

product_id | price | discountPrice
    3      |  20   | 6
    1      |  15   | 12
    2      |  13   | 0

3 个答案:

答案 0 :(得分:1)

  

我想按折扣价对结果进行排序,但如果某个product_id的discountPrice等于0,则此product_id应按价格排序。

SELECT * FROM `table` ORDER BY CASE WHEN `discountPrice` = 0 THEN `price` ELSE `discountprice` END DESC

答案 1 :(得分:0)

你使用简单, SELECT * FROM yourtable ORDER BY discountPrice DESC,price DESC

答案 2 :(得分:0)

也许你的意思是......

select *
from yourtable
order by if(discountPrice=0,price,discountPrice) descending;

在这种情况下,产品按照最低价格排列。而不是在排序列表的最低端对所有产品进行分组而不进行折扣。它们出现在价格相近的产品附近。

相关问题