MySQL 使用 MySQL,能否对一列进行排序但允许 0 出现在最后

MySQL 使用 MySQL,能否对一列进行排序但允许 0 出现在最后

您可以使用 ORDER BY 对一列进行排序,其中 0 出现在最后。语法如下−

select *from yourTableName order by yourFieldName = 0,yourFieldName;

为了理解上述概念,我们可以创建一个表。创建表的查询语句如下−

mysql> create table SortColumnZeroAtLastDemo
   −> (
   −> RankNumber int
   −> );
Query OK, 0 rows affected (1.40 sec)

现在,您可以使用以下查询语句在表中插入记录−

mysql> insert into SortColumnZeroAtLastDemo values(100);
Query OK, 1 row affected (0.20 sec)

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

mysql> insert into SortColumnZeroAtLastDemo values(0);
Query OK, 1 row affected (0.11 sec)

mysql> insert into SortColumnZeroAtLastDemo values(50);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SortColumnZeroAtLastDemo values(10);
Query OK, 1 row affected (0.15 sec)

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

mysql> insert into SortColumnZeroAtLastDemo values(40);
Query OK, 1 row affected (0.12 sec)

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

mysql> select *from SortColumnZeroAtLastDemo;

以下是输出结果−

+------------+
| RankNumber |
+------------+
|        100 |
|          0 |
|          0 |
|         50 |
|         10 |
|          0 |
|         40 |
+------------+
7 rows in set (0.00 sec)

以下是使用我们在开头讨论的语法对列进行排序并将值 0 设置为最后一个的查询语句 −

mysql> select *from SortColumnZeroAtLastDemo order by RankNumber = 0,RankNumber;

以下是输出结果−

+------------+
| RankNumber |
+------------+
|         10 |
|         40 |
|         50 |
|        100 |
|          0 |
|          0 |
|          0 |
+------------+
7 rows in set (0.00 sec)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程