MySQL - 分割左右边界值

问题描述 投票:0回答:2

我有一个案例,我将获得产品的输入,并用分隔的特殊字符分隔它们的值。使用此字符串我需要将产品及其值分离到MySQL Rows,如下所示。

输入:

{"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计数是动态的,我们每次都可以计算。请帮我在MySQL中获得上述输出。

mysql sql sp
2个回答
1
投票

MySQL唯一具有JSON功能的解决方案。

询问

 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


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一起。

© www.soinside.com 2019 - 2024. All rights reserved.