使用 MySQL 函数或过程提取 SELECT 表达式

Extract SELECT expression using MySQL function or procedure

我有兴趣通过提取 select 表达式(MySQL docs 中的 select_expr)来简化 SQL query/view。 select_expr 中的每一个本质上都是重复的,带有少量可以提取到变量中的变化。

例如,这里有一个现有的query/view。

CREATE OR REPLACE VIEW my_view AS
SELECT

  json_unquote(json_extract(sr.response, concat(SUBSTRING_INDEX(json_unquote(
    JSON_SEARCH(mt.response, 'one', 'pref.field_1', NULL, '$.f[*].q')), '.', 2), 
    '.', 'value'))) AS field_1,

  json_unquote(json_extract(sr.response, concat(SUBSTRING_INDEX(json_unquote(
    JSON_SEARCH(mt.response, 'one', 'pref.field_2', NULL, '$.f[*].q')), '.', 2), 
    '.', 'value'))) AS field_2,

  json_unquote(json_extract(sr.response, concat(SUBSTRING_INDEX(json_unquote(
    JSON_SEARCH(mt.response, 'one', 'pref.field_3', NULL, '$.f[*].q')), '.', 2), 
    '.', 'value'))) AS field_3,

FROM my_table mt;

可变位为:field_1field_2field_3

理论上,这就是我想做的:

CREATE OR REPLACE VIEW my_view AS
SELECT

  get_select_expr('field_1') AS field_1,
  get_select_expr('field_2') AS field_2,
  get_select_expr('field_3') AS field_3,

FROM my_table mt;

我一直在尝试类似下面的方法,但不确定如何让 select_expr 进行评估。它返回一个字符串是有道理的,但我不知道如何让它进行评估。也许我应该使用一个程序,但这是我的 MySQL 知识崩溃的地方。

DROP FUNCTION IF EXISTS get_select_expr;
CREATE FUNCTION get_select_expr (field_name VARCHAR(255))
RETURNS VARCHAR(255) DETERMINISTIC
RETURN concat('json_unquote(json_extract(mt.response, concat(
    SUBSTRING_INDEX(json_unquote(JSON_SEARCH(mt.response, 
    \'one\', \'pref.', field_3, '', NULL, \'$.f[*].q\')), 
    \'.\', 2), \'.\', \'value\')))');

SELECT get_select_expr('field_1') AS field_1 FROM my_table;

我已经完成了所有建议的类似问题,但没有找到我需要的。知道我可能会出错的地方或指示吗?我什至不确定我是否在寻找合适的术语。

你把代码搞得太复杂了,没必要在这里动态生成sql代码,反正也行不通。

只需创建一个将字段值和 json 字段值作为参数的函数,您不需要动态 sql:

DROP FUNCTION IF EXISTS get_select_expr;
CREATE FUNCTION get_select_expr (field_name VARCHAR(255), json_field_name varchar (255))
RETURNS VARCHAR(255) DETERMINISTIC
RETURN json_unquote(json_extract(field_name, concat(
    SUBSTRING_INDEX(json_unquote(JSON_SEARCH(field_name, 
    'one', 'pref.', json_field_name, '', NULL, '$.f[*].q')), 
    '.', 2), '.', 'value')));

SELECT get_select_expr(my_table.response, 'field_1') AS field_1 FROM my_table;