MariaDB如何使用加权按多个字段排序结果?

tquggr8v  于 2023-04-30  发布在  其他
关注(0)|答案(2)|浏览(203)

我在数据库toto上有一个products表,看起来像这样:

MariaDB [toto]> desc products;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| id         | int(11)      | NO   | PRI | NULL    |       |
| product_id | int(11)      | NO   |     | NULL    |       |
| sold_at    | datetime     | YES  |     | NULL    |       |
| rate       | int(11)      | YES  |     | NULL    |       |
| name       | varchar(128) | NO   |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+

现在我承认这些数据:

MariaDB [toto]> select * from products;
+----+------------+---------------------+----------+-----------+
| id | product_id | sold_at             | rate     | name      |
+----+------------+---------------------+----------+-----------+
|  1 |        400 | 2023-04-14 07:28:44 |     NULL | product_1 |
|  2 |        399 | NULL                |      728 | product_2 |
|  3 |        401 | 2023-04-14 07:28:44 |   100000 | product_3 |
|  4 |        398 | NULL                | 99999999 | product_4 |
|  5 |        404 | 2023-04-14 07:45:00 |        1 | product_5 |
+----+------------+---------------------+----------+-----------+
5 rows in set (0.001 sec)

我的目标是按rate DESC对所有这些结果进行排序,所有产品的sold_at值首先不是null,这意味着我希望所有非null sold_at等于1,null sold_at为0。看起来像这样:

+----+------------+---------------------+----------+-----------+
| id | product_id | sold_at             | rate     | name      |
+----+------------+---------------------+----------+-----------+
|  3 |        401 | 2023-04-14 07:28:44 |   100000 | product_3 |
|  5 |        404 | 2023-04-14 07:45:00 |        1 | product_5 |
|  1 |        400 | 2023-04-14 07:28:44 |     NULL | product_1 |
|  4 |        398 | NULL                | 99999999 | product_4 |
|  2 |        399 | NULL                |      728 | product_2 |
+----+------------+---------------------+----------+-----------+

请注意,某些产品的sold_at速率可能为NULL。

我目前尝试了多种方法,但都没有效果,例如:

WITH data AS (SELECT * FROM products ORDER BY rate DESC) SELECT * FROM data ORDER BY sold_at;
SELECT * FROM products ORDER BY rate DESC, sold_at ASC;

我知道为什么这不起作用(因为sold_at目前正在订购太使用它的日期,但我不知道如何做到)。

whlutmcx

whlutmcx1#

在MariaDB中,我们可以这样描述:

select *
from mytable
order by (sold_at is null), rate desc

order by子句的上下文中, predicate sold_at is null如果为true则计算为1,如果为false则计算为0-因此这将非空值放在第一位。
| 身份证|产品ID|出售价格|速率|名称|
| --------------|--------------|--------------|--------------|--------------|
| 三|四零一|2023-04-14 07:28:44|十万|产品3|
| 五|四零四|2023-04-14 07:45:00|1|产品中心|
| 1|四百|2023-04-14 07:28:44|联系我们|产品1|
| 四|三九八|联系我们|9999999|产品4|
| 二|三九九|联系我们|七二八|产品2|
fiddle

ctehm74n

ctehm74n2#

尝试以下操作

order by case when sold_at is null then 1 else 0 end, rate desc

相关问题