您可以借助MySQL的CHAR_LENGTH()函数按字符长度排序。该函数返回以下字符串的字符数,即4:
AMIT
要按字符长度排序字符串,以下是语法-
select *from yourTableName order by CHAR_LENGTH(yourColumnName);
为了理解上述概念,让我们首先创建一个表。以下是创建表的查询-
mysql> create table OrderByCharacterLength −> ( −> BookName varchar(200) −> );
借助insert命令将一些记录插入表中。查询如下-
mysql> insert into OrderByCharacterLength values('Let us C'); mysql> insert into OrderByCharacterLength values('Introduction to C'); mysql> insert into OrderByCharacterLength values('Data Structure And Algorithm in Java '); mysql> insert into OrderByCharacterLength values('C in Depth'); mysql> insert into OrderByCharacterLength values('Java Projects');
让我们按插入上表的顺序显示所有记录。查询如下-
mysql> select *from OrderByCharacterLength;
以下是输出-
+---------------------------------------+ | BookName | +---------------------------------------+ | Let us C | | Introduction to C | | Data Structure And Algorithm in Java | | C in Depth | | Java Projects | +---------------------------------------+ 5 rows in set (0.00 sec)
这是显示根据字符长度排列的所有记录的查询。如果列值的长度最小,那么它将获得更高的优先级,并将首先显示。
查询如下-
mysql> select *from OrderByCharacterLength order by CHAR_LENGTH(BookName);
以下是输出-
+---------------------------------------+ | BookName | +---------------------------------------+ | Let us C | | C in Depth | | Java Projects | | Introduction to C | | Data Structure And Algorithm in Java | +---------------------------------------+ 5 rows in set (0.00 sec)