繁体   English   中英

MySQL-从字符串中提取数字

[英]Mysql - extract number from string

我在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

如果模式相同,则可以使用函数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
substring_index(path,'/',-1) as number 
from table_name
;

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM