1. 程式人生 > >MySQL函式提取字串中的數字

MySQL函式提取字串中的數字

實現:用 MySQL 函式提取形如“http://www.xxx.com/hotel/detail/826457”中的數字部分

MySQL 版本:5.7

思路:

① 把字串 str0 反轉得 str1

② - str1(字元型轉整型) 得 str2

③ - str2 得 str3,反轉 str3 得 str4

④ 考慮到 str0 中會含有  '^.*[1-9]+0{n}$'  格式的資料,要擷取 str0 中自 str4 位置開始到 str0 結束的子字串作為最終提取結果

相關 sql:

mysql> use test
Database changed
mysql> show tables;
Empty set (0.00 sec)

mysql> create table test_reverse (
    -> id int unsigned not null auto_increment,
    -> url varchar(255) not null default '',
    -> primary key (id)
    -> ) engine = innodb default charset = utf8 collate = utf8_unicode_ci;
Query OK, 0 rows affected (0.34 sec)

mysql> insert into test_reverse values (null, 'http://www.zpcode.com/826457'),(null, 'http://zpcode.
org/390');
Query OK, 2 rows affected (0.11 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from test_reverse;
+----+------------------------------+
| id | url                          |
+----+------------------------------+
|  1 | http://www.zpcode.com/826457 |
|  2 | http://zpcode.org/390        |
+----+------------------------------+
2 rows in set (0.00 sec)

mysql> alter table test_reverse add number_in_string int unsigned not null;
Query OK, 0 rows affected (0.65 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> select * from test_reverse;
+----+------------------------------+------------------+
| id | url                          | number_in_string |
+----+------------------------------+------------------+
|  1 | http://www.zpcode.com/826457 |                0 |
|  2 | http://zpcode.org/390        |                0 |
+----+------------------------------+------------------+
2 rows in set (0.00 sec)

mysql> update test_reverse set number_in_string = reverse(-(-reverse(url)));
Query OK, 2 rows affected (0.12 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> select * from test_reverse;
+----+------------------------------+------------------+
| id | url                          | number_in_string |
+----+------------------------------+------------------+
|  1 | http://www.zpcode.com/826457 |           826457 |
|  2 | http://zpcode.org/390        |               39 |
+----+------------------------------+------------------+
2 rows in set (0.00 sec)

mysql> update test_reverse set number_in_string = substring(url, instr(url, number_in_string));
Query OK, 1 row affected (0.09 sec)
Rows matched: 2  Changed: 1  Warnings: 0

mysql> select * from test_reverse;
+----+------------------------------+------------------+
| id | url                          | number_in_string |
+----+------------------------------+------------------+
|  1 | http://www.zpcode.com/826457 |           826457 |
|  2 | http://zpcode.org/390        |              390 |
+----+------------------------------+------------------+
2 rows in set (0.00 sec)