比较2列的值和条件较低者如何排序?

时间:2019-06-13 08:23:39

标签: mysql select

我想比较两个价格(价格和折扣价),然后按最低价格(比较后)升序排序。

这是我的样本数据

Item | price   | discount_price
================================
1    | 2000.00 | 1500.00
2    | 89.00   |    0.00
3    | 60.00   |   50.00
4    | 59.00   |    0.00

这是我的示例代码:-

select item, price, discount_price from tableA order by
GREATEST(price,discount_price) desc

结果将显示:-

Item | price   | discount_price
================================
1    | 2000.00 | 1500.00
2    | 89.00   |    0.00
3    | 60.00   |   50.00
4    | 59.00   |    0.00

我期望的是(取其中较低者并进行相应排序)

Item | price   | discount_price
================================
1    | 2000.00 | 1500.00
2    | 89.00   |    0.00
4    | 59.00   |    0.00
3    | 60.00   |   50.00

1 个答案:

答案 0 :(得分:1)

尝试一下:

SELECT item, price, discount_price FROM tableA 
ORDER BY IF(discount_price=0,price,discount_price) DESC;

以下查询也可以:

SELECT item, price, discount_price FROM tableA 
ORDER BY CASE WHEN discount_price=0 THEN price ELSE discount_price END DESC;