mysql - MySQL 5.5 - 如何从具有重复字符串的字段中提取部分文本?
问题描述
我有这样的字段:
UPDATE</transactionType><column><name>prio</name><newValue>5</newValue><oldValue>1</oldValue><newValue>aaa<oldValue>10863321</oldValue></column></row></table></businessObjectChanges>
UPDATE</transactionType><column><name>prio</name><newValue>51</newValue><oldValue>11</oldValue><newValue>bbb<oldValue>10863321</oldValue></column></row></table></businessObjectChanges>
我正在尝试<newValue>
从左侧首先提取文本。它将是一个或两个数字/字母。另外,同时我想<oldValue>
先从左边看。所以结果是:
newValue oldValue
5 1
51 11
解决方案
由于它是一个不完整的 XML,让我们使用简单的字符串函数。
LOCATE可以找到子字符串的位置。
LEFT从开始到某个位置获取一个子字符串。
从该子字符串中,SUBSTRING_INDEX函数可以方便地获取最终标记之后的字符。
示例代码:
-- test table
drop table if exists YourTable;
create table YourTable (col varchar(1000));
-- Sample data
insert into YourTable (col) values
('UPDATE</transactionType><column><name>prio</name><newValue>5</newValue><oldValue>1</oldValue><newValue>aaa<oldValue>10863321</oldValue></column></row></table></businessObjectChanges>'),
('UPDATE</transactionType><column> <name>prio</name><newValue>51</newValue><oldValue>11</oldValue><newValue>bbb<oldValue>10863321</oldValue></column></row></table></businessObjectChanges>');
-- Query
SELECT
SUBSTRING_INDEX(LEFT(col, LOCATE('</oldValue>', col)-1),'>',-1) AS oldValue,
SUBSTRING_INDEX(LEFT(col, LOCATE('</newValue>', col)-1),'>',-1) AS newValue
FROM YourTable;
结果:
oldValue newValue
1 5
11 51
对reextester的测试在这里
边注:
在 MySql 8 中,您也可以为此使用REGEXP_SUBSTR。
SELECT
REGEXP_SUBSTR(col,'(?<=<oldValue>)[^<>]*(?=</oldValue)',1,1) as oldValue,
REGEXP_SUBSTR(col,'(?<=<newValue>)[^<>]*(?=</newValue>)',1,1) as newValue
FROM YourTable;
对db<>fiddle的测试在这里
(但请保持沉默。有些人会因为您使用正则表达式解析 XML 而皱眉。Fe here。
但话又说回来,无效的 XML 并不是真正的 XML)
推荐阅读
- javascript - 为树中的输出文件格式化 XML 不起作用
- asp.net - 在 Application Insights 指标 (VB.NET) 中为每个请求添加自定义属性
- ios - 斯威夫特:IBOutlets 停止工作的可能原因是什么?
- java - 回复中没有相关标题
- c# - 在 Datagridview 的特定列上按 EnterKey 打开新表单
- python - Pygame 没有加载图像
- android - 如何为图像添加唯一名称
- r - 在 str_extract() 之后将字符向量转换为 data.frame
- python - 熊猫数据框查找其他列的所有可能值都存在的行
- python - 有条件地替换熊猫数据框子集中的值