对数据列进行排序以在 MySQL 中检索最大文本值
为此,您可以将 ORDER BY 与一些聚合函数 right() 一起使用。我们首先创建一个数据表 -
mysql> create table DemoTable1487 -> ( -> StudentCode text -> ); Query OK, 0 rows affected (0.91 sec)
使用 insert 命令插入一些记录到数据表中 -
mysql> insert into DemoTable1487 values('560'); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable1487 values('789'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1487 values('STUDENT78'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1487 values('John89'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1487 values('Carol101'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1487 values('STUDENT98'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示数据表中的所有记录 -
mysql> select * from DemoTable1487;
这将产生以下输出 -
+-------------+ | StudentCode | +-------------+ | 560 | | 789 | | STUDENT78 | | John89 | | Carol101 | | STUDENT98 | +-------------+ 6 rows in set (0.00 sec)
这是对数据列进行排序以检索最大文本值所需的查询 -
mysql> select * from DemoTable1487 where StudentCode LIKE 'STUDENT%' -> order by cast(right(StudentCode,length(StudentCode)-length('STUDENT')) as UNSIGNED) desc -> limit 1;
这将产生以下输出 -
+-------------+ | StudentCode | +-------------+ | STUDENT98 | +-------------+ 1 row in set (0.04 sec)
广告