MySQL查询 - 从文本类型字段中提取前面带有特定字符的数字

时间:2017-01-04 11:57:40

标签: mysql

在一个MySQL数据库表中,我有一个包含Text格式值的列。让我们说列名是' test_column'和表名是' test_table'。其中一个字段/单元格值如下所示。

---
abc: 1
pqr: 1
uvw: 0
opq: 5
srt: 6
xyz: 1
qrs: 1
ijk: 1
tuv: 1
ghi: 1
---

所以,我想拿走所有这些数字并得到sum。这些值有一种唯一的格式,数字前面有冒号和空格(': ')。那么,我如何通过查询获取数字并计算总和。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:2)

<强>更新

Rajesh澄清了问题中的键值对实际上并不在不同的行中,但它们都在同一行(可能在对之间有新的行符号(\n))。鉴于此澄清,我原来的 答案对他没用。我在这里给出一个更新的答案。我认为在MySQL之外处理多个键值对的字符串更容易,并使用高级程序语言来处理它。下面我展示一个例子 使用Java。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SplitAndSumKvPairs {

    public static void main(String[] args) {
        String input = ""
                + "abc: 1\n"
                + "pqr: 1\n"
                + "uvw: 0\n"
                + "opq: 5\n"
                + "srt: 6\n"
                + "xyz: 1\n"
                + "qrs: 1\n"
                + "ijk: 1\n"
                + "tuv: 1\n"
                + "ghi: 1";

        Pattern p = Pattern.compile("\\s*(?<key>\\w+):\\s*(?<value>\\d+)");
        Matcher m = p.matcher(input);
        int sum = 0;
        while (m.find()) {
            int value = Integer.parseInt(m.group("value"));
            sum += value;
        }

        System.out.format("Given this input %s%n%nthe sum is %d", input, sum);
    }

}

该计划的输出是:

Given this input abc: 1
pqr: 1
uvw: 0
opq: 5
srt: 6
xyz: 1
qrs: 1
ijk: 1
tuv: 1
ghi: 1

the sum is 18
或者,可以尝试使用存储的函数或存储过程来表达与上面类似的逻辑。

假设键值对位于不同的行中的旧答案

select    
    sum(substring_index(test_column, ': ', -1)) 
from
    test_table  

代码已在SqlFiddle(click on this link to see it

中测试过
create table test_table (
    id              int not null primary key auto_increment
    , test_column   varchar(20) not null
) engine=innoDB;

insert into test_table
values
(null, 'abc: 1')
, (null, 'pqr: 1')
, (null, 'uvw: 0')
, (null, 'opq: 5')
, (null, 'srt: 6')
, (null, 'xyz: 1')
, (null, 'qrs: 1')
, (null, 'ijk: 1')
, (null, 'tuv: 1')
, (null, 'ghi: 1');

答案是

18