mysql - 如何编写一个 MySQL 函数来根据名称提取 JSONAttribute 的值?
问题描述
我有一个要求,我需要编写一个 mysql 函数,它将“JSONText”、“color”作为参数并基于“color”输出
[
{
"color":"red",
"points":4
},
{
"color": "Electric Blue",
"points": 5
}
]
所以,我的功能是
DELIMITER $$
CREATE FUNCTION GetColorPoints(JSONParam Text, color VARCHAR(10)) RETURNS INT
BEGIN
**???** //WHAT SHOULD GO HERE??
END$$
DELIMITER;
所以,如果我用输入调用函数,它应该给我分数。
SELECT GetColorPoints('[ {"color":"red", "points":4}, {"color": "Electric Blue", "points": 5} ]', 'Electric Blue') AS 'ColorPoints';
解决方案
如果你很高兴使用 MySQL 8.0,你可以这样做JSON_TABLE()
:
set @js = '[ { "color":"red", "points":4 }, { "color": "Electric Blue", "points": 5 } ]';
select points
from json_table(
@js,
'$[*]' columns(
color varchar(50) path '$.color',
points int path '$.points'
)
) t
where color = 'red'
推荐阅读
- javascript - 将文本添加到 DOM 元素而不导致重排以获得“渲染文本”
- c - 有没有办法不将 seccomp 过滤器继承给子进程?
- html - Bootstrap响应式文本对齐不起作用
- flutter - FlutterError:列表
不是 Map 类型的子类型 - cpu-architecture - gem5中load指令的执行过程
- python - 使用 pvlib 将时间数据转换为小时角
- oracle - 在 Oracle BI Publisher 中将数字转换为单词
- http - 理解 RFC2616 和代理服务器
- python - pip install PATH set 但 cmd 无法识别
- r - 计算数据框多列之间的百分比变化