[英]how to extract json keys and values as table with 2 columns mysql 5.7
在名为“test”的表上使用 varchar 数据类型将其放在名为“value”的列中:
'{“3”:“3”,“2”:“7”,“6”:“1”,“1”:“2”,“5”:“5”}'
output 我需要:
col1 col2
3 3
2 7
6 1
1 2
5 5
我在解析 json 时遇到了困难,因为似乎只有版本 8 提供了正确使用 json 的能力。
也许有一些想法如何解决它并动态提取键和值而无需在 col1 和 col2 中对键进行硬编码:
select 1 as 'col1', TRIM(BOTH '"' FROM (JSON_EXTRACT(value, '$."1"'))) 'col2'
from test
union all
select 2, TRIM(BOTH '"' FROM (JSON_EXTRACT(value, '$."2"')))
from test
union all
select 3, TRIM(BOTH '"' FROM (JSON_EXTRACT(value, '$."3"')))
from test
union all
select 5, TRIM(BOTH '"' FROM (JSON_EXTRACT(value, '$."5"')))
from test
union all
select 6, TRIM(BOTH '"' FROM (JSON_EXTRACT(value, '$."6"')))
from test
最好升级到 MySQL 8,这样您就可以使用 JSON_TABLE() function。
如果您需要在 SQL 表达式中引用单个元素,最好避免将数据存储在 JSON 中,而是将数据存储为普通行和列。 无论您是否升级到 MySQL 8,都是如此。
但这是您问题的解决方案:
您可以将 JSON 文档的键作为数组获取:
mysql> create table test ( value json);
mysql> insert into test set value = '{"3": "3", "2": "7", "6": "1", "1": "2", "5": "5"}';
mysql> select json_keys(value) as `keys` from test;
+---------------------------+
| keys |
+---------------------------+
| ["1", "2", "3", "5", "6"] |
+---------------------------+
pivot 这个数组成行的最简单方法是有一个整数表。
mysql> create table numbers (n int primary key);
mysql> insert into numbers (n) values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10);
mysql> select json_extract(json_keys(value), concat('$[', n, ']')) as `key`
from test cross join numbers where n <= 4;
+------+
| key |
+------+
| "1" |
| "2" |
| "3" |
| "5" |
| "6" |
+------+
现在,您可以使用此结果对您开始使用的文档进行自连接,并提取密钥。
mysql> select json_unquote(k.`key`) as col1,
json_unquote(json_extract(test.value, concat('$.', k.`key`))) as col2
from (
select json_extract(json_keys(value), concat('$[', n, ']')) as `key` from test cross join numbers where n <= 4
) as k
cross join test;
+------+------+
| col1 | col2 |
+------+------+
| 1 | 2 |
| 2 | 7 |
| 3 | 3 |
| 5 | 5 |
| 6 | 1 |
+------+------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.