【问题标题】:Mysql - extract number from stringMysql - 从字符串中提取数字
【发布时间】:2015-03-06 11:08:10
【问题描述】:

我在 mysql 表中有存储页面路径的路径字段。

页面 id 末尾有 33、31、121 ...

如何编写查询以仅获取 ID?

Path
-----
trending-architectures/architecture_detail_page/31
trending-architectures/architecture_detail_page/33
trending-architectures/architecture_detail_page/33
trending-architectures/architecture_detail_page/33
trending-architectures/architecture_detail_page/33

【问题讨论】:

  • 在 PHP 中你可以使用 preg_match_all ------------------------ preg_match_all('!\d+!', $str, $matches); print_r($matches); 或者你甚至可以使用preg_match_all("/[^0-9]/","",$str,$matches); print_r($matches);
  • 我必须在mysql的SELECT语句中这样做。
  • 所有的字符串都是相同的模式?即 2 // 之后的最后一个值是一个数字?
  • 我找不到一个单一的查询解决方案。stackoverflow.com/questions/978147/…查看这个链接。它可以帮助你...
  • 我能知道一件事吗...使用 PHP,您只需一步即可轻松完成,对吧.. 为什么要为此使用 MySQL ????

标签: php mysql


【解决方案1】:

如果模式相同,可以使用函数substring_index()

mysql> select substring_index('trending-architectures/architecture_detail_page/31','/',-1) as num;
+-----+
| num |
+-----+
| 31  |
+-----+
1 row in set (0.00 sec)

所以 select 语句会变成

select
substring_index(path,'/',-1) as number 
from table_name
;

【讨论】:

  • Hii @Abhik Chakraborty ...我认为他最后甚至有三个数字(例如 121、122、....).. 这个查询在这种情况下是否有效??
  • 如果模式相同,它将从末尾获取任何数字。
【解决方案2】:

我可以想到两种解决方案,第一个利用explode将字符串拆分为一个数组,使用“/”deliemeter,然后将数组的最后一个值(即页面id)设置在一个变量中

$path = explode('/', $path);
$page = end($path);

其他解决方案只是用任何内容替换数字之前的任何文本

$page = str_replace('trending-architectures/architecture_detail_page/', '', $path);

【讨论】:

  • 在 php 中我可以。我必须在 mysql 的 SELECT 语句中执行此操作。
猜你喜欢
  • 2019-01-04
  • 2011-10-13
  • 2021-11-27
  • 2016-06-24
  • 1970-01-01
相关资源
最近更新 更多