MySQL 按首字母排序?


为了按首字母排序,请使用 ORDER BY CASE 语句。下面我们先创建一个表格 -

mysql> create table DemoTable1535
   -> (
   -> Value varchar(100)
   -> );
Query OK, 0 rows affected (2.26 sec)

使用 insert 命令在表格中插入一些记录 -

mysql> insert into DemoTable1535 values('MySQL is good relational database.');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1535 values('is MySQL easy to lean');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable1535 values('You need to start basic SQL');
Query OK, 1 row affected (0.35 sec)

使用 select 语句从表格中显示所有记录 -

mysql> select * from DemoTable1535;

这将生成以下输出 -

+------------------------------------+
| Value                              |
+------------------------------------+
| MySQL is good relational database. |
| is MySQL easy to lean              |
| You need to start basic SQL        |
+------------------------------------+
3 rows in set (0.00 sec)

以下查询是按首字母排序的 -

mysql> select * from DemoTable1535
    -> order by case when left(Value, 1) = 'i' then 1 else 2 end,Value;

这将生成以下输出 -

+------------------------------------+
| Value                              |
+------------------------------------+
| is MySQL easy to lean              |
| MySQL is good relational database. |
| You need to start basic SQL        |
+------------------------------------+
3 rows in set (0.00 sec)

更新于:12-12-2019

481 浏览量

启动您的 职业

通过完成课程获得认证

开始吧
广告