mysql ORDER BY IF ELSE

时间:2013-08-29 11:32:23

标签: mysql

我在想是否有更高级的方法在mysql查询中使用ORDER BY

我有查询从db获取产品,使用按价格排序。 问题是如果折扣价值不为空,它会覆盖主要价格,而且应该以某种方式 覆盖ORDER BY行。

IDEA:

DESC

product_price discount
900           0
800           0
1200          700 //dicount overrides price
600           0



查询有25行,但逻辑是这样的:

SELECT
product_price as price,
IFNULL(discount_amount,0) as discount

FROM not_relevant

WHERE not_relevant

ORDER BY product_price DESC

因此,当我根据价格将产品写入类别时,某些产品会有折扣,因此主要价格会被覆盖,仅按价格排序并不准确。

我尝试使用coalesce或两个ORDER BY

有什么想法吗? 谢谢你的帮助。

3 个答案:

答案 0 :(得分:3)

我认为这应该适合你:

SELECT
product_price,
IFNULL(discount_amount,0) as discount,
IFNULL(discount_amount,product_price) as price

FROM not_relevant

WHERE not_relevant

ORDER BY price DESC

它基本上就是你所要求的...如果discount不为空,则会使用它,否则它会使用product_price,并对结果进行排序。

答案 1 :(得分:2)

如果折扣实际是折扣价而非折扣金额,则可以使用此

SELECT product_price as price,
IFNULL(discount_amount,0) as discount

FROM not_relevant
    ORDER BY 
CASE WHEN discount_amount IS NULL THEN price ELSE discount_amount END

答案 2 :(得分:1)

SELECT product_price As price
     , Coalesce(discount_amount, 0) As discount
     , Coalesce(discount_amount, product_price) As order_by_this
FROM   not_relevant
WHERE  not_relevant
ORDER
    BY order_by_this

可替换地:

SELECT product_price As price
     , Coalesce(discount_amount, 0) As discount
FROM   not_relevant
WHERE  not_relevant
ORDER
    BY Coalesce(discount_amount, product_price)