MySQL 查询对值大于零的行进行排序?

mysqlmysqli database

首先我们创建一个表。以下是查询 −

mysql> create table gettingAndOrderingRowsDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Value int
   -> );
Query OK, 0 rows affected (1.35 sec)

下面是使用 insert 命令在表中插入一些记录的查询 −

mysql> insert into gettingAndOrderingRowsDemo(Value) values(10);
Query OK, 1 row affected (0.33 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(13);
Query OK, 1 row affected (0.32 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(0);
Query OK, 1 row affected (0.17 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(20);
Query OK, 1 row affected (0.26 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(30);
Query OK, 1 row affected (0.50 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(60);
Query OK, 1 row affected (0.24 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(0);
Query OK, 1 row affected (0.28 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(45);
Query OK, 1 row affected (0.15 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(0);
Query OK, 1 row affected (0.69 sec)

以下是使用 select 语句显示表中的所有记录的查询 −

mysql> select * from gettingAndOrderingRowsDemo;

这将产生以下输出 −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 10    |
| 2  | 13    |
| 3  | 0     |
| 4  | 20    |
| 5  | 30    |
| 6  | 60    |
| 7  | 0     |
| 8  | 45    |
| 9  | 0     |
+----+-------+
9 rows in set (0.00 sec)

以下是查询大于零的值 −

mysql> select * from gettingAndOrderingRowsDemo
-> order by Value=0,Value;

这将产生以下输出 −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 10    |
| 2  | 13    |
| 4  | 20    |
| 5  | 30    |
| 8  | 45    |
| 6  | 60    |
| 3  | 0     |
| 7  | 0     |
| 9  | 0     |
+----+-------+
9 rows in set (0.00 sec)

相关文章