Count json tags in sql

不羁的心 提交于 2020-06-23 10:26:08

问题


I have this json strings

[{"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"}]

And know i want the following output

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

I wanted to do this with a sql query. If you know how to do this, thanks in advance!


回答1:


If you're not using MySQL 8, this is a bit more complicated. First you have to find a path to a name element that has the value phone (or fixkit); then you can replace name in that path with count and extract the count field from that path; these values can then be summed:

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

Output:

param   count
fixkit  9
phone   16

Demo on dbfiddle




回答2:


If you are running MySQL 8.0, you can unnest the arrays into rows with json_table(), then filter on the names you are interested in, and aggregate.

Assuming that your table is mytable and that the json column is called js, that would be:

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

Demo on DB Fiddle:

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


来源:https://stackoverflow.com/questions/62398600/count-json-tags-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!