从MySQL中的XML字符串中选择查询

时间:2016-11-26 12:39:19

标签: mysql xpath

我有XML字符串,它有多个子节点,我想从下面的子节点获取数据是一个示例结构,我想获取所有结果节点。尝试在 MySQL

中使用此查询
SET @xml= '<aaa><result>
        <id>1</id>
        </result>
        <result>
        <id>2</id>
        </result>
         ....
    </aaa>';
SELECT  ExtractValue(@xml, '/aaa/result/id/text()[1]');

当前输出

1 2

预期输出

1
2

如果有最好的方法可以告诉我吗?

1 个答案:

答案 0 :(得分:1)

我是通过将列分成两列

来实现的
SET @xml= '<aaa><result>
        <id>1</id>
        </result>
        <result>
        <id>2</id>
        </result>
    </aaa>';

SELECT
        SUBSTRING_INDEX(ExtractValue(@xml, '//id'), ' ', 1) AS `id1`,
        SUBSTRING_INDEX(ExtractValue(@xml, '//id'), ' ', -1) AS `id2`

<强>输出

id1   |    id2
1     |     2

正如你所说的结果节点可以是多个,为此我尝试了下面的查询

SET @xml= '<aaa><result>
        <id>1</id>
        </result>
        <result>
        <id>2</id>
        </result>
        <result>
        <id>3</id>
        </result>
        <result>
        <id>4</id>
        </result>
        <result>
        <id>5</id>
        </result>
        <result>
        <id>7</id>
        </result>
        <result>
        <id>6</id>
        </result>
        <result>
        <id>8</id>
        </result>
        <result>
        <id>9</id>
        </result>
        <result>
        <id>10</id>
        </result>
        <result>
        <id>11</id>
        </result>        
    </aaa>';

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(ExtractValue(@xml, '//id'), ' ', n.n), ' ', -1) value
  FROM (select SUBSTRING_INDEX(ExtractValue(@xml, '//id'), ' ', 1)) t CROSS JOIN 
  (
   SELECT a.N + b.N * 10 + 1 n
     FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n 
   ) n
 WHERE n.n <= 1 + (LENGTH(ExtractValue(@xml, '//id')) - LENGTH(REPLACE(ExtractValue(@xml, '//id'), ' ', '')))

<强>输出

Value

1
2
3
4
5
7
6
8
9
11