[英]Mysql: Split one column with number and letter to two
I have a table like this: 我有一张这样的桌子:
Product|weight
A |5kg
B |5.2kg
C |3.9kg
D |6l
I would like to split the second columns to have a table looking like this: 我想拆分第二列以使表看起来像这样:
Product|weight|unit
A |5 |kg
B |5.2 |kg
C |3.9 |kg
D |6 |l
How do I do it? 我该怎么做? I found an answer here Split value from one field to two , but this seems only to work if you have a separator.
我在这里找到了将值从一个字段拆分为两个的答案,但这似乎只有在使用分隔符的情况下才有效。
For just the data you show in the example: 对于示例中显示的数据:
CRATE TABLE foo (product varchar(7), weight varchar(7));
INSERT INTO foo VALUES ('A','5kg'),('B','5.2kg'),('C','3.9kg'),('D','6l')
This will work: 这将起作用:
SELECT t.product
, t.weight
, t.weight + 0 AS num
, REPLACE(t.weight,t.weight+0,'') AS unit
FROM foo t
BUT... 但...
This won't work in the more general case, consider: 这在更一般的情况下不起作用,请考虑:
INSERT INTO foo VALUES ('E','1.00kg'),('F','02m'),('G','0kg'),('H','10ppm10')
The "trick" the query is using is to evaluate the column weight in a numeric context, by adding a zero. 查询使用的“技巧”是通过在数字上下文中添加零来评估列权重。 MySQL will return the numeric value.
MySQL将返回数值。
What doesn't really work is getting the units portion. 真正不起作用的是获取单位部分。 In the special case where the numeric value converted to a string exactly matches the leading string in the
weight
column, the REPLACE function can be used to replace that string with a zero length string. 在特殊情况下,如果转换为字符串的数值与
weight
列中的前导字符串完全匹配,则可以使用REPLACE函数将该字符串替换为零长度的字符串。 We have the same problem with SUBSTRING and the CHAR_LENGTH function; 我们对SUBSTRING和CHAR_LENGTH函数有同样的问题。 I don't have a good solution.
我没有一个好的解决方案。
A better approach to getting the "unit" may be to compare to a specified list of units. 获取“单位”的更好方法可能是与指定的单位列表进行比较。
, CASE
WHEN t.weight LIKE '%kg' THEN 'kg'
WHEN t.weight LIKE '%g' THEN 'g'
WHEN t.weight LIKE '%ml' THEN 'ml'
WHEN t.weight LIKE '%l' THEN 'l'
ELSE ''
END AS unit
Using this approach, it's important to check for the "longest" strings before the shorter strings (eg if we checked for '%l'
before we check for '%ml'
, we'd get 'l'
returned rather than 'ml'
). 使用这种方法,重要的是在较短的字符串之前检查“最长”的字符串(例如,如果我们在检查
'%ml'
之前检查了'%l'
'%ml'
,我们将得到'l'
而不是'ml'
)。
NOTE The MySQL REGEXP
operator is limited, it only returns a boolean; 注意 MySQL
REGEXP
运算符是有限的,它只返回一个布尔值。 indicating whether an expression matches a pattern, it won't return a location or a portion of the string that matched the pattern. 指示表达式是否与模式匹配,它将不会返回与模式匹配的位置或字符串的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.