mysql 查第一个_如何使用MySQL查询在文本字段中找到第一个数字?

bd96500e110b49cbb3cd949968f18be7.png

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.

I tried to

SELECT SUBSTR(the_field, LOCATE('2', the_field, 1)) AS 'the_number'

FROM the_table

and it works. But how to get ANY number?

I tried

SELECT SUBSTR(the_field, LOCATE(REGEXP '[0-9], the_field, 1)) AS 'the_number'

FROM the_table

but this time I get an error.

Any ideas?

解决方案SELECT REGEXP_SUBSTR(`the_field`,'^[0-9]+') AS `the_number` FROM `the_table`;

Notes:

I'm using MySQL Server v8.0.

This pattern assumes that the_field is trimmed. Otherwise, use TRIM() first.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用定时任务存储JSON字符串并查询数据的示例: 1. 创建数据表 假设我们要存储一个 JSON 字符串到一个名为 `my_table` 的数据表,该表包含两个字段:`id` 和 `data`。其,`id` 是一个自增长的整数,`data` 是一个长文本类型的字段,用于存储 JSON 字符串。 ``` CREATE TABLE my_table ( id INT PRIMARY KEY AUTO_INCREMENT, data LONGTEXT ); ``` 2. 编写定时任务脚本 我们可以使用 Python 的第三方库 `schedule` 来编写一个定时任务脚本,该脚本每隔一分钟就向 `my_table` 数据表插入一个随机生成的 JSON 字符串。 ```python import json import random import schedule import time import mysql.connector # 连接 MySQL 数据库 db = mysql.connector.connect( host="localhost", user="root", password="password", database="my_database" ) # 定义一个任务函数 def insert_data(): # 生成一个随机的 JSON 字符串 data = { "name": "John Doe", "age": random.randint(18, 60), "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" } } json_data = json.dumps(data) # 插入数据到 my_table 表 cursor = db.cursor() sql = "INSERT INTO my_table (data) VALUES (%s)" val = (json_data,) cursor.execute(sql, val) db.commit() print("Inserted data:", json_data) # 定义一个每分钟执行一次的任务 schedule.every(1).minutes.do(insert_data) # 不断运行定时任务 while True: schedule.run_pending() time.sleep(1) ``` 3. 查询数据 我们可以使用 MySQL 的 `JSON_EXTRACT()` 函数来查询 `my_table` 表的 JSON 数据。例如,如果我们要查询所有年龄大于 30 岁的人的信息,可以使用以下 SQL 语句: ``` SELECT * FROM my_table WHERE JSON_EXTRACT(data, '$.age') > 30; ``` 该语句使用 `JSON_EXTRACT()` 函数从 `data` 字段提取 `age` 属性,并与 30 进行比较。如果 `age` 大于 30,则返回该行数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值