【问题标题】:MySQL ORDER BY two clauses (descending and ascending)MySQL ORDER BY 两个子句(降序和升序)
【发布时间】:2019-12-16 14:55:55
【问题描述】:

我有这张桌子:

create table products(name text, quantity int);
insert into products values ("A", 10);
insert into products values ("B", 0);
insert into products values ("C", 15);
insert into products values ("D", 0);
insert into products values ("E", 17);

我想按产品名称订购,但请保留底部带有quantity = 0 的产品,如下所示:

name    quantity
A       10
C       15
E       17
B       0
D       0

我试过了: select * from products order by quantity desc, name asc; 但它虽然正确地将 quantity = 0 保留在底部,但名称顺序是相反的。在这种情况下使用ORDER BY 是否正确?

SQL 小提琴:http://sqlfiddle.com/#!9/6985a4/1/0

【问题讨论】:

    标签: mysql sql sql-order-by


    【解决方案1】:

    我会使用:

    order by (quantity = 0), name
    

    布尔值按“false”排序,然后“true”排序。

    我会使用它来表示明确,而不是使用诸如'z' 之类的特殊值——如果您的名称以'z' 开头,这甚至不起作用。

    【讨论】:

      【解决方案2】:

      试试这个:

      select * from products 
      order by case when quantity = 0 then "z" else name end asc;
      

      【讨论】:

      • 。 .如果您想要以z 开头的名称,例如'zip',这将不起作用。
      • 好点 GL,就像你用我的句柄来证明它的方式 :-)
      【解决方案3】:

      你可以这样试试:

      SELECT * FROM (
      select name, quantity from products WHERE quantity>0 order by name) t1
      UNION
      select name, quantity from products t2 WHERE quantity<=0;
      

      【讨论】:

      • 会返回什么样的错误?在作者提供的网站上检查它 - sqlfiddle.com/#!9/6985a4/1/0 ,一切正常。
      • 你在 union 之前有一个“order by”。您发送的 sqlfiddle,没有使用“union”关键字。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多