仅按照 MySQL 的升序排列显示记录的列表
要按特定顺序显示记录列表,您需要设置条件并使用 ORDER BY。为此,请使用 ORDER BY CASE 语句。首先,让我们创建一个表 -
mysql> create table DemoTable2039 -> ( -> Name varchar(20) -> ); Query OK, 0 rows affected (0.62 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable2039 values('John Doe'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable2039 values('John Smith'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable2039 values('Chris Brown'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable2039 values('Adam Smith'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable2039 values('David Miller'); Query OK, 1 row affected (0.09 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable2039;
这将产生以下输出 -
+--------------+ | Name | +--------------+ | John Doe | | John Smith | | Chris Brown | | Adam Smith | | David Miller | +--------------+ 5 rows in set (0.00 sec)
以下是按升序显示特定记录列表的查询 -
mysql> select *from DemoTable2039 -> order by -> case when Name like '%Smith%' then 101 -> else -> 100 -> end, -> Name;
这将产生以下输出 -
+--------------+ | Name | +--------------+ | Chris Brown | | David Miller | | John Doe | | Adam Smith | | John Smith | +--------------+ 5 rows in set (0.37 sec)
广告