mysql - 将具有空值或空值的字段转换为 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'} |
--------------------------------
谢谢。
解决方案
我得到解决方案...
如果有人对解决方案感兴趣....
有了这些数据:
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 的评论,它让我走上了正轨!:)
推荐阅读
- javascript - 下载不会用javascript下载
- javascript - 如何减少此代码中的变量和 if 语句的数量?
- slider - Jssor 滑块 - 有没有办法从停止状态启动滑块?
- postgresql - 使用 SSH 隧道通过 DBeaver 连接到 Postgres
- android - 使用 SSID/密码测试 wifi 网络而不连接它
- mysql - MySQL 返回与设置不同的日期格式
- python - Python - 以相对于元组元素的降序和相对于另一个元素的升序对元组列表进行排序
- selenium - 通过 selenium 可以使用哪个 By 元素来识别这个标签?
- python - bqplot 中的错误?轴限制的意外行为
- perl - 在子例程中传递全局变量的值