Skip to content

Instantly share code, notes, and snippets.

@wd0517
Last active December 1, 2022 07:29
Show Gist options
  • Save wd0517/ae880559f4d0e65bc86c6d3c09bfc428 to your computer and use it in GitHub Desktop.
Save wd0517/ae880559f4d0e65bc86c6d3c09bfc428 to your computer and use it in GitHub Desktop.
CREATE TABLE `t1` (
`jdoc` json DEFAULT NULL
)
insert into t1 values ('[3,4]');
insert into t1 values ('[1,2]');
# https://stackoverflow.com/questions/39906435/convert-json-array-in-mysql-to-rows
SELECT
JSON_EXTRACT(jdoc, CONCAT('$[', idx, ']')) AS item, count(*)
FROM t1
JOIN (
SELECT 0 AS idx UNION
SELECT 1 AS idx UNION
SELECT 2 AS idx UNION
SELECT 3
) AS indexes
WHERE JSON_EXTRACT(jdoc, CONCAT('$[', idx, ']')) IS NOT NULL
GROUP BY 1
# use JSON_TABLE in MySQL 8+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment