【问题标题】:Convert fields with empty or null values to JSON data on MYSQL将具有空值或空值的字段转换为 MYSQL 上的 JSON 数据
【发布时间】:2019-03-15 14:33:38
【问题描述】:

我有一张表,其中包含几个字段,我想在一个 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'} |
--------------------------------

谢谢。

【问题讨论】:

  • 稍后我也想用这句话在json字段中插入数据...类似于update lead set tagData = json_remove(...
  • 因为 SQL 和 JSON 都是声明性语言,这种组合使得在不知道示例数据和预期结果的情况下无法回答这个问题。请参阅Why should I provide an MCVE for what seems to me to be a very simple SQL query? 以提供示例数据和预期结果...
  • 我添加了示例数据
  • 必须是动态的还是列数已知且固定?
  • @RaymondNijland 非常感谢您的评论,它让我找到了解决方案。

标签: mysql json field


【解决方案1】:

我得到了解决方案...

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

有了这些数据:

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 的评论,它让我走上了正轨! :)

【讨论】:

  • 是的,我很感兴趣。谢谢你。它没有直接帮助我,但我从中学到了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
相关资源
最近更新 更多