MySQL - 有条件地构建JSON_OBJECT

时间:2017-06-27 22:53:12

标签: mysql json

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

# Return the start and (1-past-the-end) indices of the first instance of
# at least min_count copies of element value in container l 
def find_repeat(value, min_count, l):
  look_for = [value for _ in range(min_count)]
  for i in range(len(l)):
    count = 0
    while l[i + count] == value:
      count += 1
    if count >= min_count:
      return i, i + count

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

1 个答案:

答案 0 :(得分:0)

一个选项是:

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)