2

我有一个 MySQL数据库表ds_message,它包含模板和 JSON 对象。我想用 JSON 键找到模板字符串中存在的键,并用 JSON 值替换键。

桌子:

_____________________________________________________________________________________
id  template                                  key_value
_____________________________________________________________________________________
1  'Dear {a}, the price of {b} is {c}'       '{"a":"John", "b":"bat", "c":"$10"}'
2  'Dear {i}, you selected the product {j}'  '{"i":"Emma", "j":"Jam"}'

我需要 SQL Select 语句来获取字符串Dear John, the price of bat is $10,并且每个模板都有 N 个键,它在整个表中并不相同。

表结构:

CREATE TABLE `ds_message` (
  `id` int NOT NULL,
  `template` varchar(500) NOT NULL,
  `key_value` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='';

ALTER TABLE `ds_message`
  ADD PRIMARY KEY (`id`);

INSERT INTO `ds_message` (`id`, `template`, `key_value`) VALUES
(1, 'Dear {a}, the price of {b} is {c}', '{"a":"John", "b":"bat", "c":"$10"}');

INSERT INTO `ds_message` (`id`, `template`, `key_value`) VALUES
(2, 'Dear {i}, you selected the product {j}', '{"i":"Emma", "j":"Jam"}');

预期结果:

  1. 亲爱的约翰,蝙蝠的价格是 10 美元
  2. 亲爱的 Emma,您选择了 Jam 产品

请在 SELECT 语句或存储过程中帮助我。

4

1 回答 1

1

这是一种方法,将 JSON 路径表达式与REPLACE函数一起使用:

WITH ds_message AS (
    SELECT 1 AS id, 'Dear {a}, the price of {b} is {c}' AS template, '{"a":"John", "b":"bat", "c":"$10"}'AS key_value
)

SELECT
    id,
    template,
    key_value,
    REPLACE(
        REPLACE(
            REPLACE(template, '{c}', key_value->"$.c"),
                '{b}', key_value->"$.b"),
                    '{a}', key_value->"$.a") AS output
FROM ds_message;

这将输出以下内容output

Dear "John", the price of "bat" is "$10"
于 2019-08-21T06:49:28.750 回答