将具有空值或空值的字段转换为 MYSQL 上的 JSON 数据

Convert fields with empty or null values to JSON data on MYSQL

我有一个 table,其中有几个字段,我想将它们编译到一个 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'} |
--------------------------------

谢谢。

我找到了解决方案...

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

有了这个数据:

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"}                             |

这里是DB Fiddle

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