【问题标题】:In MySQL how to get numbers after a specific word在MySQL中如何获取特定单词后的数字
【发布时间】:2019-08-19 21:34:57
【问题描述】:

我有一张包含产品描述的表格。这些描述中包含产品尺寸,但并非全部位于同一位置。

如何从以下示例数据中仅提取数字宽度 说明

  • 桌宽(厘米)100
  • 床,宽度:90cm
  • 办公桌宽度 - 200 厘米。颜色 - 黑色
  • 500厘米宽的沙发
  • 椅子-宽(50.5cm)

已使用 substring_index 函数获取 'width' 和 'cm' 之间的文本,但无法获取其中的数字。 (这不适用于上面的记录 1

SELECT description, substring_index(substring_index(description, 'width', -1),'cm', 1)
FROM productlisting 

预期输出:

  • 100
  • 90
  • 200
  • 500
  • 50.5

实际

  • : 90
    • 200
  • 共 500 个
  • (50.5

【问题讨论】:

  • 输入不一致,这将是一场斗争。您可能需要多次解析数据以处理每种情况
  • 这可能会有所帮助。 stackoverflow.com/questions/37268248/…
  • 从不超过一个数字?
  • 重新设计数据库以使其更加用户友好是否为时已晚?
  • 使用 regex_replace() 就像 select regex_replace(description,'[^0-9]','')

标签: mysql sql


【解决方案1】:

在 MySQL 8+ 中,您可以使用regexp_replace() 获取“宽度”之后的第一个数字

select regexp_replace(d, '.*Width[^0-9]*', '') + 0

【讨论】:

  • 谢谢 Gordon,我应该提一下,但是我们仍然使用 MySQL 5.7。所以我对这个不走运。另一个升级的原因,但是负责数据库的人有些犹豫。
  • 你好,戈登。设法将表转储到 8.0 数据库中。我正在使用 MySQL Workbench 来运行查询,但是除非我的限制设置得非常低(
  • @MarkMcP 。 . .我真的不明白你的评论。
  • 在 MySQL 工作台中我运行: select regexp_replace(description, '.*Width[^0-9]*', '') from productlist + 0 系统然后抛出消息:错误代码:3699 . 正则表达式匹配超时。 0.204 秒
【解决方案2】:

如果描述中只有 1 个数字,就像您的示例数据一样,您可以使用 Mysql string functions 获取该数字,如下所示:

select
  p.description,
  substr(p.description, min(locate(d.digit, p.description))) + 0 number
from (
  select 0 digit union all select 1 union all
  select 2 union all select 3 union all
  select 4 union all select 5 union all
  select 6 union all select 7 union all
  select 8 union all select 9 
) d inner join productlisting p
on p.description like concat('%', d.digit, '%')
group by p.description 

请参阅demo
结果:

|description                                | number |
| ----------------------------------------- | ------ |
| Bed, Width: 90cm                          | 90     |
| Chair - width(50.5cm)                     | 50.5   |
| Couch with Width of 500 cm                | 500    |
| Office Desk Width - 200 cm. Color - Black | 200    |
| Table Width (cm) 100                      | 100    |

【讨论】:

  • 很遗憾,尽管我的示例数据已简化,但非常感谢。实际数据可以有超过 1 个数字,例如:-“宽度 680mm 高度 920mm 重量 23Kg 5Ft 选项规格长度 1460mm”
  • 更好地改变你的设计。当没有要搜索的模式时,Sql 代码无法在描述中的任何位置发现其他数字中的数字。
  • 希望就这么简单。数据来自其他来源和各地。我们将研究更先进的解决方案。欢呼
猜你喜欢
  • 2013-06-19
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
相关资源
最近更新 更多