MySQL-分隔定界的右和左值

时间:2019-03-09 16:17:10

标签: mysql sql sp

在某些情况下,我将获取产品输入,并用定界的特殊字符分隔其值。使用此字符串,我需要将产品及其值分离到如下所示的MySQL行中。

输入:

{"1301":29.00,"1302":25.01,"1306":50.09,"1678":100.00}

输出:

Product ID      Value
1301             29.00
1302             25.01
1306             50.09
1678             100.00

这里的产品ID计数是动态的,我们每次都能获得n个计数。请帮助我在MySQL中获得以上输出。

2 个答案:

答案 0 :(得分:1)

您确实应该像JSON一样对待它,但是您可以使用强力字符串方法。这是一种方法:

select replace(substring_index(str, ':', 1), '"', '') as product_id, substring_index(str, ':', -1) as value
from (select replace(replace(substring_index(@x, ',', 1), '{', ''), '}', '') as str) x
union all
select replace(substring_index(str, ':', 1), '"', '') as product_id, substring_index(str, ':', -1) as value
from (select replace(replace(substring_index(substring_index(@x, ',', 2), ',', -1), '{', ''), '}', '') as str) x
union all
select replace(substring_index(str, ':', 1), '"', '') as product_id, substring_index(str, ':', -1) as value
from (select replace(replace(substring_index(substring_index(@x, ',', 3), ',', -1), '{', ''), '}', '') as str) x
union all
select replace(substring_index(str, ':', 1), '"', '') as product_id, substring_index(str, ':', -1) as value
from (select replace(replace(substring_index(substring_index(@x, ',', 4), ',', -1), '{', ''), '}', '') as str) x;

以及db<>fiddle

答案 1 :(得分:1)

仅JSON功能的MySQL解决方案。

查询

 SELECT 
  TRIM(REPLACE(
    SUBSTRING_INDEX(
       SUBSTRING_INDEX(json_parsed, ',', number_generator.number)
       , ','
       , -1
     )
     , '"'
     , ''
   ))  AS 'Product ID'
 , JSON_EXTRACT(json, CONCAT('$.', SUBSTRING_INDEX(
     SUBSTRING_INDEX(json_parsed, ',', number_generator.number)
     , ','
     , -1
   ))) AS 'Value'
FROM (

  SELECT 
   @row := @row + 1 AS number
  FROM (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION   SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) row1
  CROSS JOIN (
    SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION  SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
  ) row2
  CROSS JOIN (
    SELECT @row := 0 
  ) init_user_params 
) AS number_generator
CROSS JOIN (

    SELECT  
        SUBSTRING(json_keys, 2, json_keys_length - 2) AS json_parsed
      , json_keys
      , json
      , JSON_LENGTH(json_keys) AS json_array_length                       
    FROM (
       SELECT 
            JSON_KEYS(record.json) AS json_keys
          , json
          , LENGTH(JSON_KEYS(record.json)) AS json_keys_length
       FROM (
          SELECT 
             '{"1301":29.00,"1302":25.01,"1306":50.09,"1678":100.00}' AS json
          FROM  
            DUAL  
       ) AS record                     
    ) AS json_information  
  ) AS json_init
WHERE
 number_generator.number BETWEEN 0 AND json_array_length

结果

| Product ID | Value |
| ---------- | ----- |
| 1301       | 29.0  |
| 1302       | 25.01 |
| 1306       | 50.09 |
| 1678       | 100.0 |

请参阅demo