2

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

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

主意:

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

有任何想法吗?感谢帮助。

4

3 回答 3

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不是 null ,它将被使用,否则它将使用product_price,并对结果进行排序。

于 2013-08-29T11:38:32.013 回答
1

如果折扣实际上是折扣价而不是折扣金额,则可以使用此选项

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
于 2013-08-29T11:38:11.357 回答
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)
于 2013-08-29T11:38:48.533 回答