因此,我想按价格订购产品-- ASC
和DESC
,但有些产品将在数据库中填写discountprice
列,如果是的话,应该考虑到它们,而不是price
字段。
所以目前我有这样一个:SELECT * FROM products ORDER BY price ASC
,但是我如何也可以为特定产品的ORDER
子句附加一些类似if (discountprice != '' AND discountprice != NULL) then use discount price
的东西呢?
发布于 2015-06-07 23:32:49
你可以这样做:
SELECT (price-IFNULL(discountprice,0)) as finalprice FROM products
ORDER BY finalprice ASC
如果要按discountprice
列排序,可以通过两种方式进行:
IFNULL
:
选择*从产品订单按IFNULL(折扣价格,价格) ASCCOALESCE
:
从按合并订购的产品中选择*(折扣价格,价格)发布于 2015-06-07 23:29:33
使用COALESCE
选择第一个非空值:
SELECT * FROM products
ORDER BY coalesce(discountprice, price) ASC
如果出于某种原因,也有空字符串作为NULL,则使用常规CASE
。
SELECT * FROM products
ORDER BY CASE when discountprice is NOT NULL
or discountprice != '' THEN discountprice
else price end ASC
发布于 2015-06-07 23:29:33
尝尝这个
SELECT * FROM products ORDER BY
case when (discountprice != '' or discountprice != NULL)
then
(price-discountprice)
else
price
end
ASC
https://stackoverflow.com/questions/30703349
复制