首页 > 解决方案 > 将具有空值或空值的字段转换为 MYSQL 上的 JSON 数据

问题描述

我有一张表,其中包含多个字段,我只想在一个 json 字段中进行编译。问题是这些列中有几个 null 和 emtpy 字符串值,并且您不想将它们放在 json 中,只需存储相关值即可。我想用尽可能少的查询来做到这一点。

这是我目前的方法:

    select
       json_remove(
         json_remove(json, json_search(json, 'one', 'null')),
         json_search(json, 'all', '')
       ) result
    from (
       select
              json_object(
                  'tag_1', coalesce(tag_1, 'null'),
                  'tag_2', coalesce(tag_2, 'null'),
                  'tag_3', coalesce(tag_3, 'null')
                ) json
       from leads
     ) l2;

但问题是 json_search 输出与 json_remove 输入不兼容。有任何想法吗?

以下是一些示例数据:

-------------------------
| tag_1 | tag_2 | tag_3 |
-------------------------
|   x   |       |  null |
|       |   y   |   z   |
-------------------------

我认为结果是:

--------------------------------
| result                       |
--------------------------------
| {'tag_1': 'x'}               |
| {'tag_2': 'y', 'tag_3': 'z'} |
--------------------------------

谢谢。

标签: mysqljsonfield

解决方案


我得到解决方案...

如果有人对解决方案感兴趣....

有了这些数据:

CREATE TABLE t (
  id INT(11) unsigned not null auto_increment,
  `tag_1` VARCHAR(255),
  `tag_2` VARCHAR(255),
  `tag_3` VARCHAR(255),
  primary key (id)
);

INSERT INTO t
  (`tag_1`, `tag_2`, `tag_3`)
VALUES
  ('x', '', null),
  ('x','x', null),
  ('x', '', 'x'),
  ('x','x','x'),
  (null, null, 'x')
  ;

这是查询:

select id, json_objectagg(field, val) as JSON  from (
  select id, 'tag_1' field, tag_1 val from t union
  select id, 'tag_2' field, tag_2 val from t union 
  select id, 'tag_3' field, tag_3 val from t
) sub where val is not null and val != ''
group by sub.id;

子查询对要使用的数据进行透视JSON_OBJECTAGG

id  field   val
1   tag_1   x
2   tag_1   x
3   tag_1   x
4   tag_1   x
5   tag_1   null
1   tag_2   ''
2   tag_2   x
...

然后用 json_objectagg 分组就可以了!

| id  | JSON                                       |
| --- | ------------------------------------------ |
| 1   | {"tag_1": "x"}                             |
| 2   | {"tag_1": "x", "tag_2": "x"}               |
| 3   | {"tag_1": "x", "tag_3": "x"}               |
| 4   | {"tag_1": "x", "tag_2": "x", "tag_3": "x"} |
| 5   | {"tag_3": "x"}                             |

这是数据库小提琴

非常感谢@Raimond Nijland 的评论,它让我走上了正轨!:)


推荐阅读