设一个表数据包含两列
id | 零件 |
---|---|
1 | {"1":1,"2":0,"3":2,"4":0;"5":0} |
2 | 空 |
3 | {"6":1,"7":0} |
4 | {"3":1} |
5 | null |
我设法使用Alexey的答案从这个问题中得到了一个解决方案mysql-json元素的总和,分组并全选,但我发现它有点笨拙:
with data_not_null as
(
SELECT * FROM data
WHERE data.parts IS NOT NULL
AND data.parts != CAST('null' AS JSON)
)
SELECT id, SUM(JSON_EXTRACT(CONCAT('$."', key, '"'))) sum_parts
FROM data_not_null,
JSON_TABLE(CAST(JSON_KEYS(parts->'$.') AS JSON), '$[*]' COLUMNS(key VARCHAR(2) PATH '$') t
GROUP BY id