SQL按两列排序,忽略null

Dav*_*vid 4 mysql sql sorting

我有一个包含两列的表,如下所示:

  1. 价格(varchar)
  2. 折扣(varchar)

这两个保存了我数据库中所有产品的价格和折扣。当用户查看产品时,我有多种排序模式可用,其中之一是Sort by price: low to high. 为了做到这一点,我有以下代码:

$stmt = $link->prepare("SELECT ... ORDER BY `discount` ASC, `price` ASC, `title` ASC");
Run Code Online (Sandbox Code Playgroud)

discount这对于定义的所有行都适用,但在discount为空的行中,它们会排序在其他行之上,无论 的值如何price

例如:

id|price|discount
-----------------
 1|20   |10
 2|25   |10
 3|15   |
 4|15   |
Run Code Online (Sandbox Code Playgroud)

将按顺序回显:

3, 4, 1, 2
Run Code Online (Sandbox Code Playgroud)

如何重写此语句以在没有值price时进行排序?discount

sge*_*des 5

您可以COALESCE为此使用:

SELECT ... 
ORDER BY COALESCE(`discount`, `price`), `price`, `title`
Run Code Online (Sandbox Code Playgroud)

如果它不为空,这将首先 order by discount,然后 order by price。对于那些具有相同折扣的商品,它将按 排序price,然后是title

注意:根据您想要的结果,您可能希望通过 删除附加订单price