gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:46:53 24 4
gpt4 key购买 nike

我有一个 MySQL 表,其定义如下:

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

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

mysql> select * from person;
+----+------+----------------------------------+
| id | name | fruits |
+----+------+----------------------------------+
| 1 | Tom | ["apple", "orange"] |
| 2 | John | ["apple", "mango"] |
| 3 | Tony | ["apple", "mango", "strawberry"] |
+----+------+----------------------------------+

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

+------------+-------+
| fruit | count |
+------------+-------+
| apple | 3 |
| orange | 1 |
| mango | 2 |
| strawberry | 1 |
+------------+-------+

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

最佳答案

您可以使用 JSON_EXTRACT() 函数提取数组的所有三个组件的每个值(“apple”、“mango”、“strawberry”和“orange”),然后应用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

确实如果你的数据库版本是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;

Demo

关于mysql - 如何计算 MySQL JSON 数组中每个值的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59292894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com