0

我有一个要求,我需要编写一个 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';
4

1 回答 1

1

如果你很高兴使用 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'
于 2020-03-30T22:21:56.360 回答