在表格列中提供以下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
答案 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)
<强>更新强>
检查:
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)