我有一个包含两列的表:
这两个包含我数据库中所有产品的价格和折扣。当用户查看产品时,我有多种可用的排序模式,其中一种是Sort by price: low to high
。为此,我有以下代码:
$stmt = $link->prepare("SELECT ... ORDER BY `discount` ASC, `price` ASC, `title` ASC");
这适用于定义discount
的所有行,但在discount
为空的行中,无论price
的值是什么,它们都会排在其他行之上。
例如:
id|price|discount
-----------------
1|20 |10
2|25 |10
3|15 |
4|15 |
将按顺序回显:
3, 4, 1, 2
当price
没有值时,如何重写此语句以按discount
排序?
答案 0 :(得分:3)
您可以使用COALESCE
:
SELECT ...
ORDER BY COALESCE(`discount`, `price`), `price`, `title`
如果discount
不为空,则首先按price
排序,然后按price
排序。对于具有相同折扣的商品,它将按title
订购,然后按price
订购。
注意:根据您所需的结果,您可能希望按{{1}}删除其他订单。
答案 1 :(得分:0)
尝试使用IFNULL? ,我已在SQLfiddle
上创建了示例查询select * from product order by IFNULL(discount,price)