【发布时间】: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 非常感谢您的评论,它让我找到了解决方案。