gpt4 book ai didi

MySQL:JSON 到结果集

转载 作者:可可西里 更新时间:2023-11-01 09:00:02 27 4
gpt4 key购买 nike

我有一个存档表,其中有一列包含未索引的 json 记录。示例:

[{
"attr1": "val1",
"attr2": "val2",
"attr3": "val3",
.
.
"attrN": "valN"
}, {
"attr1": "val1.2",
"attr2": "val2.2",
"attr3": "val3.2",
.
.
"attrN": "valN.2"
},...]

我需要创建一个将 json 作为结果集返回的存储过程或函数:

  attr1   |   attr2    |   attr3  | ... |  attrN
_______________________________________________
val1 | val2 | val3 | ... | valN
val1.2 | val2.2 | val2.2 | ... | valN.2

我需要它作为记录集返回,因为我将它用于其他存储过程中的其他查询。

我能够通过以下方式实现这一目标:Read JSON array in MYSQL

但是我想知道除了创建临时表还有别的方法吗?我在考虑性能和效率。比如,如果 20 或 50 个用户触发了这个怎么办?有更好的方法吗?

注意:json 的平均大小约为 1MB

最佳答案

此存储过程创建一个动态查询,输出您需要的结果,应使用真实数据进行测试以检查性能是否足够好:

CREATE PROCEDURE jsonToCols(IN json JSON, IN target VARCHAR(50))
BEGIN
SET @j = 0;
SET @fields = JSON_KEYS(json, "$[0]");
SET @f_length = JSON_LENGTH(@fields);
SET @select = "";
WHILE @j < JSON_LENGTH(json) DO
SET @i = 0;
SET @select = CONCAT(@select, "SELECT ");
WHILE @i < @f_length DO
SET @attr_name = REPLACE(JSON_EXTRACT(@fields, CONCAT("$[", @i, "]")), '\"', '');
SET @key = CONCAT('$.', @attr_name);
SET @select = CONCAT(@select, "JSON_EXTRACT(json, '$[", @j , "].", @attr_name, "') as ", @attr_name, ", ");
SET @i = @i + 1;
END WHILE;

SET @select = CONCAT(LEFT(@select, length(@select)-2), " FROM ", target ," UNION ALL ");
SET @j = @j + 1;
END WHILE;

SET @select = LEFT(@select, length(@select)-11);

PREPARE stmt FROM @select;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;

动态创建的查询如下所示:

SELECT JSON_EXTRACT(json, '$[0].attr1') as attr1, JSON_EXTRACT(json, '$[0].attr2') as attr2, JSON_EXTRACT(json, '$[0].attr3') as attr3, JSON_EXTRACT(json, '$[0].attrN') as attrN 
FROM test
UNION ALL
SELECT JSON_EXTRACT(json, '$[1].attr1') as attr1, JSON_EXTRACT(json, '$[1].attr2') as attr2, JSON_EXTRACT(json, '$[1].attr3') as attr3, JSON_EXTRACT(json, '$[1].attrN') as attrN
FROM test

FIDDLE

关于MySQL:JSON 到结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47524981/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com