count json标记

lf3rwulv  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(307)

我有这个json字符串

[{"count": 9, "name": "fixkit", "label": "Repair Kit"}, {"count": 1, "name": "phone", "label": "Telefoon"}]
[{"count": 3, "name": "phone", "label": "Telefoon"}]
[{"count": 5, "name": "kunststof", "label": "Kunststof"}, {"count": 6, "name": "papier", "label": "Papier"}, {"count": 2, "name": "metaal", "label": "Metaal"}, {"count": 2, "name": "inkt", "label": "Inkt"}, {"count": 3, "name": "kabels", "label": "Kabels"}, {"count": 2, "name": "klei", "label": "Klei"}, {"count": 2, "name": "glas", "label": "Glas"}, {"count": 12, "name": "phone", "label": "Telefoon"}]
[{"count": 77, "name": "weed", "label": "Cannabis"}, {"count": 1, "name": "firework1", "label": "Vuurpijl 1"}]

我想得到以下结果

Phone | Number of phones (in this case: 16)
Fixkit | Number of fixkits (in this case: 9)

我想用sql查询来实现这一点。如果你知道怎么做,请提前感谢!

6jjcrrmo

6jjcrrmo1#

如果您不使用mysql 8,这就有点复杂了。首先你要找到一条通往 name 具有值的元素 phone (或 fixkit ); 然后你可以替换 name 在那条路上 count 并提取 count 从那条路来的田地;这些值可以相加:

SELECT param, SUM(JSON_EXTRACT(counts, REPLACE(JSON_UNQUOTE(JSON_SEARCH(counts, 'one', param, NULL, '$[*].name')), 'name', 'count'))) AS count
FROM data
CROSS JOIN (
  SELECT 'phone' AS param
  UNION ALL
  SELECT 'fixkit'
) params
WHERE JSON_SEARCH(counts, 'one', param, NULL, '$[*].name') IS NOT NULL
GROUP BY param

输出:

param   count
fixkit  9
phone   16

在dbfiddle上演示

pobjuy32

pobjuy322#

如果您运行的是mysql 8.0,那么可以使用 json_table() ,然后在 name 你感兴趣的是什么。
假设你的table是 mytable json列被称为 js ,即:

select j.name, sum(j.cnt) cnt
from mytable t
cross join json_table (
    t.js,
    '$[*]' columns(
        cnt int          path '$.count',
        name varchar(50) path '$.name'
    )
) j
where j.name in ('phone', 'fixkit')
group by j.name

db小提琴演示:

| name   | cnt |
| ------ | --- |
| fixkit | 9   |
| phone  | 16  |

相关问题