MySQL 先按 0 排序,然后按降序显示记录?
若要先按 0 排序,然后再按最大值排序,可以使用以下语法 −
select *from yourTableName order by yourColumnName=0 DESC,yourColumnName DESC;
我们先创建一个表 −
mysql> create table DemoTable ( Value int ); Query OK, 0 rows affected (0.65 sec)
使用 insert 命令在表中插入记录 −
mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(70); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable values(0); Query OK, 1 row affected (0.15 sec)
使用 select 命令从表中显示记录 −
mysql> select *from DemoTable;
这会产生以下输出 −
+-------+ | Value | +-------+ | 90 | | 0 | | 20 | | 0 | | 10 | | 70 | | 0 | +-------+ 7 rows in set (0.00 sec)
以下是按 0 排序然后按降序显示最大元素的查询 −
mysql> select *from DemoTable order by Value=0 DESC,Value DESC;
这会产生以下输出 −
+-------+ | Value | +-------+ | 0 | | 0 | | 0 | | 90 | | 70 | | 20 | | 10 | +-------+ 7 rows in set (0.00 sec)
广告