【问题标题】:Find and Replace a String usng a Json Key Value pair object in MySQL在 MySQL 中使用 Json 键值对对象查找和替换字符串
【发布时间】:2019-12-26 09:03:54
【问题描述】:

我有一个 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 语句或存储过程中帮助我。

【问题讨论】:

  • 你用的是什么版本的 MySQL?
  • @TimBiegeleisen - MySQL 5.7 和 8

标签: mysql json replace key-value mysql-json


【解决方案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"

【讨论】:

  • 我在这里面临的问题是,关键值将是所有记录不一致的任何东西,一条记录可能有 x,y,z 而另一条记录可能有 j,k.. ..我对你的努力投了赞成票。你能帮帮我吗?
  • 那么 MySQL 不是进行这些替换的最佳场所。
  • 我明确地修改了问题 - 更新版本。
  • 我不认为你可以不使用动态 SQL(例如在存储过程中)做你想做的事。
  • 没有问题...请您通过存储过程分享您的想法,我也在尝试。
猜你喜欢
  • 2021-05-13
  • 2022-06-15
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 2012-07-09
  • 1970-01-01
  • 2020-01-20
相关资源
最近更新 更多