如何实现 MySQL ORDER BY x where (x=col3 if col3!=null, else x=col2)?

mysqlmysqli database更新于 2024/1/30 14:23:00

为此,您可以使用 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 的查询,其中(x=col3 if col3!=null, else 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)

相关文章