从值中提取字符串并插入到字段中

时间:2015-07-11 21:49:34

标签: mysql substring

这是mytable:

+----+-------------+  
| id | data        |  
+----+-------------+  
|  1 | DA-1111 A   |  
|  2 | DA-5334 B   |  
|  3 | DA-4532 A   |  
|  4 | DA-34 K     |  
+----+-------------+  

使用查询:

select substring_index(substring_index(myfield, '-', -1), ' ', 1) as colB from mytable

我在DA-和最后一个字母之间得到了引用值。现在我想要从字段中提取值,同时将该值插入到同一个表中的新字段中。最终结果应该是:

+----+-------------+------+  
| id | data        | colB |
+----+-------------+------+  
|  1 | DA-1111 A   | 1111 |  
|  2 | DA-5334 B   | 5334 | 
|  3 | DA-4532 A   | 4532 | 
|  4 | DA-34 K     | 34   | 
+----+-------------+------+

这可能吗?怎么做?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

update mytable
set colB = substring_index(substring_index(myfield, '-', -1), ' ', 1)

当然,该表应该已经有一个名为colB的字段,否则您可以使用ALTER TABLE语句创建它。