MySQL 查询按一组数字中的第一个数字排序?

mysqlmysqli database更新于 2025/12/23 19:56:17

要按一组数字中的第一个数字排序,请使用 ORDER BY SUBSTRING_INDEX()。让我们首先创建一个表 −

mysql> create table DemoTable
(
   SetOfNumbers text
);
Query OK, 0 rows affected (0.53 sec)

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

mysql> insert into DemoTable values('245,654,76,89,98');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('2000,567,9090,6789');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('1001,90595,657,99');
Query OK, 1 row affected (0.20 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 −

+--------------------+
| SetOfNumbers       |
+--------------------+
| 245,654,76,89,98   |
| 2000,567,9090,6789 |
| 1001,90595,657,99  |
+--------------------+
3 rows in set (0.00 sec)

以下是按一组数字中的第一个数字排序的查询 −

mysql> select *from DemoTable order by cast(substring_index(SetOfNumbers,',',1) as unsigned);

这将产生以下输出 −

+--------------------+
| SetOfNumbers       |
+--------------------+
| 245,654,76,89,98   |
| 1001,90595,657,99  |
| 2000,567,9090,6789 |
+--------------------+
3 rows in set (0.00 sec)

相关文章


有用资源