我有这张表:
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 amount desc, name asc;
但是,虽然它正确地将 quantity = 0
保留在底部,但名称顺序却相反。在这种情况下使用 ORDER BY
是否正确?
SQL fiddle :http://sqlfiddle.com/#!9/6985a4/1/0
最佳答案
我会使用:
order by (quantity = 0), name
bool 值的排序顺序为“false”,然后是“true”。
我会使用它来显式地使用它,而不是使用诸如 'z'
之类的特殊值 - 如果您的名称以 'z' 开头,这甚至不起作用
.
关于MySQL ORDER BY 两个子句(降序和升序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59359120/