MySQL 查詢按 NULL 值排序
我們首先建立一個表 -
mysql> create table DemoTable707 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(100), StudentMarks int ); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令在表中插入一些記錄 -
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values('John',45);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values(NULL,65);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values('Chris',78);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values(NULL,89);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values('Robert',99);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values(NULL,34);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable707(StudentFirstName,StudentMarks) values('Mike',43);
Query OK, 1 row affected (0.20 sec)使用 select 語句從表中顯示所有記錄 -
mysql> select *from DemoTable707;
這會產生以下輸出 -
+-----------+------------------+--------------+ | StudentId | StudentFirstName | StudentMarks | +-----------+------------------+--------------+ | 1 | John | 45 | | 2 | NULL | 65 | | 3 | Chris | 78 | | 4 | NULL | 89 | | 5 | Robert | 99 | | 6 | NULL | 34 | | 7 | Mike | 43 | +-----------+------------------+--------------+ 7 rows in set (0.00 sec)
以下是按 NULL 值排序的查詢 -
mysql> select *from DemoTable707 order by StudentFirstName IS NULL, StudentFirstName DESC;
這會產生以下輸出 -
+-----------+------------------+--------------+ | StudentId | StudentFirstName | StudentMarks | +-----------+------------------+--------------+ | 5 | Robert | 99 | | 7 | Mike | 43 | | 1 | John | 45 | | 3 | Chris | 78 | | 2 | NULL | 65 | | 4 | NULL | 89 | | 6 | NULL | 34 | +-----------+------------------+--------------+ 7 rows in set (0.00 sec)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP