如何按ID分组并汇总所有行JSON编码数据

时间:2019-05-30 05:12:38

标签: php mysql sql json

I have Faced group by some id and Sum other column json_encode data in select query MySQL.
But how to sum total json data value?
Please help Anyone...

使用此,     PHP 7.2,Mysql 5和Apache 2。

I am try code
    > SELECT `fk_club_id`,`adpoints`,`actpoints`,(JSON_OBJECT('actpoints',
    > actpoints, 'adpoints', adpoints)) FROM (SELECT `fk_club_id`,
    > SUM(JSON_EXTRACT("$.adpoints")) as adpoints,
    > SUM(JSON_EXTRACT("$.actpoints")) as actpoints FROM club_scoresheet
    > where status= 1 GROUP BY `fk_club_id`) as t

我的表格数据

    id  |  JSON  column()

    15    ['5','6','2']
    15    ['5','6','2']
    28    ['5','6','1']
    28    ['5','6','1']
    28    ['5','6','1']

这是我的桌子

我的期望结果,

id  | JSON column( total)

15     26
28     36

预期结果

1 个答案:

答案 0 :(得分:1)

在MySQL 5.7版中,引入了可以解决您的问题的JSON函数。您可以使用以下内容,但是仅当JSON中包含固定数量的项目时,才允许检索总和。您的示例指出,每​​个JSON数组中都有3个项目,因此您应该没事:

SELECT ID, SUM(CAST(JSON_EXTRACT(JSON,'$[0]') AS UNSIGNED)+CAST(JSON_EXTRACT(JSON,'$[1]') AS UNSIGNED)+CAST(JSON_EXTRACT(JSON,'$[2]') AS UNSIGNED)) AS TOTAL FROM TEST GROUP BY ID;

如果要升级到MySQL 8,还可以使用新的JSON_TABLE函数来处理JSON数组中的任意数量的项目:

SELECT TEST.ID,SUM(t.VAL) AS TOTAL FROM TEST, JSON_TABLE(JSON, '$[*]' COLUMNS(VAL INT PATH '$')) t GROUP BY ID

您也可以在this db fiddle中进行测试。