从 MySQL 中使用字符串值(字符串、数字和特殊字符)获取列中的特定记录
为此,你可以使用 ORDER BY CAST()。让我们看一个示例 −
mysql> create table DemoTable2006 ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserCode varchar(20) ); Query OK, 0 rows affected (1.14 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable2006(UserCode) values('John_12'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable2006(UserCode) values('John_34'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2006(UserCode) values('John_56'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable2006(UserCode) values('Chris_101'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable2006(UserCode) values('Chris_103'); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable2006(UserCode) values('Chris_106'); Query OK, 1 row affected (0.07 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable2006;
这将产生以下输出 −
+--------+-----------+ | UserId | UserCode | +--------+-----------+ | 1 | John_12 | | 2 | John_34 | | 3 | John_56 | | 4 | Chris_101 | | 5 | Chris_103 | | 6 | Chris_106 | +--------+-----------+ 6 rows in set (0.00 sec)
以下是从列中获取特定记录的查询 −
mysql> select * from DemoTable2006 where UserCode like 'John%' order by cast(substring(UserCode from 7) as signed) desc limit 1;
这将产生以下输出 −
+--------+----------+ | UserId | UserCode | +--------+----------+ | 3 | John_56 | +--------+----------+ 1 row in set (0.00 sec)
广告