MYSQL 分组并计数在 JSON 列
MYSQL group by and count on JSON column
我有一个 sql table json 这样的数据
id | int(11) Primary Key
reasons | json
在 json_data 列我存储了数组。
id| reasons
1 | ["price","inactive","small","other"]
2 | ["price","other"]
3 | ["price","inactive"]
我需要按“原因”分组并计算数量
price | 3
inactive | 2
small | 1
other | 2
我试过了;
$dealInvestors = Deal::select(
"JSON_CONCAT(decline_reasons,'$.$all_possible_reasons)",
'count(reasons) as count',
)
->groupBy('reasons')
->get();
但是没有用。
谁能帮帮我?
SELECT reason, COUNT(*)
FROM test
CROSS JOIN JSON_TABLE(test.reasons,
'$[*]' COLUMNS (reason VARCHAR(255) PATH '$')
) jsontable
GROUP BY reason
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=43cdbb8bfca8aa3cd3e82ccf775a577e
PS。我怀疑此查询是否可以转换为 Laravel 语法。使用原始 SQL.
我有一个 sql table json 这样的数据
id | int(11) Primary Key
reasons | json
在 json_data 列我存储了数组。
id| reasons
1 | ["price","inactive","small","other"]
2 | ["price","other"]
3 | ["price","inactive"]
我需要按“原因”分组并计算数量
price | 3
inactive | 2
small | 1
other | 2
我试过了;
$dealInvestors = Deal::select(
"JSON_CONCAT(decline_reasons,'$.$all_possible_reasons)",
'count(reasons) as count',
)
->groupBy('reasons')
->get();
但是没有用。 谁能帮帮我?
SELECT reason, COUNT(*)
FROM test
CROSS JOIN JSON_TABLE(test.reasons,
'$[*]' COLUMNS (reason VARCHAR(255) PATH '$')
) jsontable
GROUP BY reason
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=43cdbb8bfca8aa3cd3e82ccf775a577e
PS。我怀疑此查询是否可以转换为 Laravel 语法。使用原始 SQL.