MySQL中按字符数排序的方法

要按字符数排序,请使用ORDER BY和LENGTH()方法。以下是语法-

select *from yourTableName order by LENGTH(yourColumnName) DESC;

让我们首先创建一个表-

mysql− create table DemoTable
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.50 sec)

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

insert into DemoTable values('John');
insert into DemoTable values('Robert');
insert into DemoTable values('Bob');
insert into DemoTable values('David');

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

select *from DemoTable;

输出结果

+--------+
| Name   |
+--------+
| John   |
| Robert |
| Bob    |
| David  |
+--------+
4 rows in set (0.00 sec)

以下是按字符数排序的查询-

select *from DemoTable order by LENGTH(Name) DESC;

输出结果

+--------+
| Name   |
+--------+
| Robert |
| David  |
| John   | 
| Bob    |
+--------+
4 rows in set (0.00 sec)