MySQL -有条件地构建JSON_OBJECT

ssm49v7z  于 2023-03-07  发布在  Mysql
关注(0)|答案(2)|浏览(163)

是否可以有条件地构建json对象,例如:

mysql> SELECT JSON_OBJECT(
      CASE
        WHEN some_condition THEN key, val
        ELSE
           // do nothing 
        END CASE

    );

如果没有,我怎样有条件地构建一个json对象呢?基本上我只想包含非空的属性。

jbose2ul

jbose2ul1#

一种选择是:

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)
u5rb5r59

u5rb5r592#

我们可以使用JSON_MERGE_PATCH来有条件地合并JSON对象。
JSON_MERGE_PATCH会忽略值为NULL的对象,因此,只要条件不成立,我们就可以构建值为NULL的JSON对象,否则就正常创建。

    • 架构(MySQL v8.0)**
    • 查询#1**
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;

| 结果|
| - ------|
| {"键1 ":"值1 "}|
View on DB Fiddle

相关问题