如何使用MySQL查询在文本字段中找到第一个数字? [英] How to find the first number in a text field using a MySQL query?
本文介绍了如何使用MySQL查询在文本字段中找到第一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想返回存储在数据库表列中的文本的第一个数字. 用户已将页面范围放入"p.2-5"或第2至5页"或"2-5"之类的字段中. 我对这里的"2"很感兴趣.
I like to return only the first number of a text stored in a column of a database table. User have put in page ranges into a field like 'p.2-5' or 'page 2 to 5' or '2 - 5'. I am interested in the '2' here.
我试图
SELECT SUBSTR(the_field, LOCATE('2', the_field, 1)) AS 'the_number'
FROM the_table
,并且有效.但是,如何获得任何数字?
and it works. But how to get ANY number?
我尝试了
SELECT SUBSTR(the_field, LOCATE(REGEXP '[0-9], the_field, 1)) AS 'the_number'
FROM the_table
但是这次我得到一个错误.
but this time I get an error.
有什么想法吗?
推荐答案
只需使用 REGEXP_SUBSTR():
SELECT REGEXP_SUBSTR(`the_field`,'^[0-9]+') AS `the_number` FROM `the_table`;
注意:
- 我正在使用MySQL Server v8.0.
- 此模式假定已修剪
the_field
.否则,请先使用TRIM().
- I'm using MySQL Server v8.0.
- This pattern assumes that
the_field
is trimmed. Otherwise, use TRIM() first.
这篇关于如何使用MySQL查询在文本字段中找到第一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文