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

时间:2019-03-15 14:33:38

标签: mysql json field

我有一张表,其中有几个字段,我只想在一个json字段中进行编译。问题在于这些列中有几个null和emtpy字符串值,y不想将它们放在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'} |
--------------------------------

谢谢。

1 个答案:

答案 0 :(得分:0)

我找到了解决方法...

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

使用此数据:

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的评论,这使我步入正轨! :)