如何计算 MySQL JSON 数组中每个值的计数?

Arj*_*jun 3 mysql sql json mysql-8.0

我有一个MySQL具有以下定义的表:

mysql> desc person;
+--------+---------+------+-----+---------+-------+
| Field  | Type    | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| id     | int(11) | NO   | PRI | NULL    |       |
| name   | text    | YES  |     | NULL    |       |
| fruits | json    | YES  |     | NULL    |       |
+--------+---------+------+-----+---------+-------+
Run Code Online (Sandbox Code Playgroud)

该表有一些示例数据如下:

mysql> select * from person;
+----+------+----------------------------------+
| id | name | fruits                           |
+----+------+----------------------------------+
|  1 | Tom  | ["apple", "orange"]              |
|  2 | John | ["apple", "mango"]               |
|  3 | Tony | ["apple", "mango", "strawberry"] |
+----+------+----------------------------------+
Run Code Online (Sandbox Code Playgroud)

如何计算每种水果出现的总数?例如:

+------------+-------+
| fruit      | count |    
+------------+-------+
| apple      | 3     |
| orange     | 1     |
| mango      | 2     | 
| strawberry | 1     |
+------------+-------+
Run Code Online (Sandbox Code Playgroud)

一些研究表明该JSON_LENGTH功能可以使用,但我找不到与我的场景类似的示例。

Bar*_*han 8

您可以使用JSON_EXTRACT()函数提取数组的所有三个组件的每个值(“苹果”、“芒果”、“草莓”和“橙色”),然后应用UNION ALL来组合所有此类查询:

SELECT comp, count(*)
FROM
(
 SELECT JSON_EXTRACT(fruit, '$[0]') as comp FROM person UNION ALL
 SELECT JSON_EXTRACT(fruit, '$[1]') as comp FROM person UNION ALL
 SELECT JSON_EXTRACT(fruit, '$[2]') as comp FROM person 
) q
WHERE comp is not null
GROUP BY comp
Run Code Online (Sandbox Code Playgroud)

事实上如果你的数据库版本是8,那么你也可以使用JSON_TABLE()函数:

SELECT j.fruit, count(*)
  FROM person p
  JOIN JSON_TABLE(
                 p.fruits,
                '$[*]' columns (fruit varchar(50) path '$')
       ) j
GROUP BY j.fruit;
Run Code Online (Sandbox Code Playgroud)

Demo