如何在 (x=col3 如果 col3!=null,否則 x=col2) 的情況下實現 MySQL ORDER BY x?


為此,你可以使用 ORDER BY IFNULL()。讓我們首先建立一個表 −

mysql> create table DemoTable
   -> (
   -> Name varchar(20),
   -> CountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.61 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable values('Chris',NULL);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('David','AUS');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(NULL,'UK');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(NULL,'AUS');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(NULL,NULL);
Query OK, 1 row affected (0.11 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將生成以下輸出 −

+-------+-------------+
| Name  | CountryName |
+-------+-------------+
| Chris | NULL        |
| David | AUS         |
| NULL  | UK          |
| NULL  | AUS         |
| NULL  | NULL        |
+-------+-------------+
5 rows in set (0.00 sec)

以下是實現 MySQL ORDER BY x where (x=col3 如果 col3!=null,否則 x=col2) 的查詢 −

mysql> select *from DemoTable
   -> order by ifnull(Name,CountryName);

這將生成以下輸出 −

+-------+-------------+
| Name  | CountryName |
+-------+-------------+
| NULL  | NULL        |
| NULL  | AUS         |
| Chris | NULL        |
| David | AUS         |
| NULL  | UK          |
+-------+-------------+
5 rows in set (0.00 sec)

更新日期:2019-12-17

68 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.