mysql> SET @`key` = 'key',
-> @`val` = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT
-> CASE WHEN @`key` IS NOT NULL AND @`val` IS NOT NULL THEN
-> JSON_OBJECT(@`key`, @`val`)
-> END `json`;
+------------+
| json |
+------------+
| {"key": 1} |
+------------+
1 row in set (0.00 sec)
mysql> SET @`key` = 'key',
-> @`val` = NULL;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT
-> CASE WHEN @`key` IS NOT NULL AND @`val` IS NOT NULL THEN
-> JSON_OBJECT(@`key`, @`val`)
-> END `json`;
+------+
| json |
+------+
| NULL |
+------+
1 row in set (0.01 sec)
SELECT JSON_MERGE_PATCH(
-- Following key will exist because condition is success
JSON_OBJECT('key1', CASE WHEN 1 /* some condition here */ THEN 'value1' ELSE NULL END),
-- Following key will not exist because condition fails
JSON_OBJECT('key2', CASE WHEN 0 /* some condition here */ THEN 'value2' ELSE NULL END)
) as result;
2条答案
按热度按时间jbose2ul1#
一种选择是:
u5rb5r592#
我们可以使用
JSON_MERGE_PATCH
来有条件地合并JSON对象。JSON_MERGE_PATCH
会忽略值为NULL
的对象,因此,只要条件不成立,我们就可以构建值为NULL
的JSON对象,否则就正常创建。| 结果|
| - ------|
| {"键1 ":"值1 "}|
View on DB Fiddle