Count json tags in sql

前端 未结 2 607
自闭症患者
自闭症患者 2021-01-24 06:31

I have this json strings

[{\"count\": 9, \"name\": \"fixkit\", \"label\": \"Repair Kit\"}, {\"count\": 1, \"name\": \"phone\", \"label\": \"Telefoon\"}]
[{\"coun         


        
2条回答
  •  走了就别回头了
    2021-01-24 07:03

    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

提交回复
热议问题