首页 > 解决方案 > 如何编写一个 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';

标签: mysqlsqlmysql-function

解决方案


如果你很高兴使用 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'

推荐阅读