[英]How to extract 1st and 2nd number from a formatted alphanumeric string using SQL?
Example data in a weight
column (from 3 rows of data) weight
列中的示例数据(来自3行数据)
+-------------------------+
| weight |
+-------------------------+
| Pump:398kg Motor:0kg |
| Pump:448# Motor:997# |
| Pump:355kg Motor:2495kg |
+-------------------------+
Is there a way to extract the first number from column, and the 2nd number in the column separately? 有没有办法分别从列中提取第一个数字和列中的第二个数字?
Note 注意
Pump:
Pump:
开头Pump:
Motor:
will always be in the middle Motor:
永远在中间 #
or kg
, there are no others #
或kg
,没有其他 My goal is to split the numbers each into their own column 我的目标是将数字分成各自的列
ie 即
UPDATE table set weight_pump = ?, weight_motor = ?
UPDATE table set weight_pump = 398, weight_motor = 0
I can solve this using PHP (SELECT each row, do REGEX to extract numbers, write back to the row) 我可以使用PHP解决此问题(选择每一行,执行REGEX提取数字,写回该行)
But what I am looking for is a pure SQL solution, if such exists. 但是,我正在寻找的是纯SQL解决方案(如果存在)。 Preferably a single SQL statement, if exists but I am not opposed to several statements or intermediate steps.
最好有一个SQL语句(如果存在),但我不反对几个语句或中间步骤。
I have seen other answers but they focus on extracting a single number from SQL, I am seeking something more powerful. 我看到了其他答案,但它们专注于从SQL提取单个数字,我正在寻找更强大的功能。
Note: it can be also done in two steps (one for "kg", one for "#") to simplify query. 注意:也可以分两个步骤完成(一个用于“ kg”,一个用于“#”)以简化查询。
Here's a solution, using substring_index(). 这是使用substring_index()的解决方案。
I like this function because it doesn't depend so much on specific character positions. 我喜欢这个功能,因为它并不太依赖特定的字符位置。
mysql> SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(weight, ':', -2), 'kg', 1), '#', 1) AS weight_pump,
SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(weight, ':', -1), 'kg', 1), '#', 1) AS weight_motor
FROM MyTable;
Output: 输出:
+-------------+--------------+
| weight_pump | weight_motor |
+-------------+--------------+
| 398 | 0 |
| 448 | 997 |
| 355 | 2495 |
+-------------+--------------+
This works with UPDATE too: 这也适用于UPDATE:
mysql> UPDATE MyTable
SET weight_pump = SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(weight, ':', -2), 'kg', 1), '#', 1),
weight_motor = SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(weight, ':', -1), 'kg', 1), '#', 1);
Read more about this function here: http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index 在此处阅读有关此功能的更多信息: http : //dev.mysql.com/doc/refman/5.7/zh-CN/string-functions.html#function_substring-index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.