如何使用JSON函数对Mariadb中的json字段求值

时间:2017-07-09 13:54:47

标签: mysql arrays json mariadb

在表格列中提供以下json字段:

[
  {
    "payment_date":"2016-04-26",
    "amount":590,
    "payment_method":"2"
  },
  {
    "payment_date":"2017-05-01",
    "amount":208,
    "payment_method":"4"
  }
]

我如何汇总所有金额?

我能得到的最远的是

SELECT JSON_EXTRACT(`payment_lines`, '$[*].amount') FROM tbl

返回:

[590, 208]

我需要得到的是590和208的总和。所以说在这种情况下有两行但可能还有更多。

SELECT VERSION();
10.2.6-MariaDB-10.2.6+maria~jessie-log

1 个答案:

答案 0 :(得分:2)

尝试:

MariaDB [(none)]> SELECT VERSION();
+-----------------------+
| VERSION()             |
+-----------------------+
| 10.2.6-MariaDB-10.2.6 |
+-----------------------+
1 row in set (0.00 sec)

MariaDB [(none)]> SET @`JSON` := '
    '> [
    '>   {
    '>     "payment_date":"2016-04-26",
    '>     "amount":590,
    '>     "payment_method":"2"
    '>   },
    '>   {
    '>     "payment_date":"2017-05-01",
    '>     "amount":208,
    '>     "payment_method":"4"
    '>   }
    '> ]';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> SELECT
    ->   JsonGet_Int(
    ->     JSON_EXTRACT(@`JSON`, '$[*].amount'),
    ->     '[+]'
    ->   ) `SUM`;
+------+
| SUM  |
+------+
|  798 |
+------+
1 row in set (0.00 sec)

请参阅CONNECT JSON Table Type

<强>更新

检查:

MariaDB [(none)]> SHOW VARIABLES WHERE `Variable_name` = 'plugin_dir';
+---------------+------------------------+
| Variable_name | Value                  |
+---------------+------------------------+
| plugin_dir    | /usr/lib/mysql/plugin/ |
+---------------+------------------------+
1 row in set (0.00 sec)

MariaDB [(none)]> \! ls -1 /usr/lib/mysql/plugin/ | grep 'ha_connect'
ha_connect.so

MariaDB [(none)]> CREATE FUNCTION IF NOT EXISTS jsonget_int RETURNS integer
    -> SONAME 'ha_connect.so';
Query OK, 0 rows affected (0.00 sec)