Mysql:获取json数组长度并忽略空值

Mysql: get json array length and ignore null values

我有这个问题

select json_length(data->"$.row.*.code") as count from hospitalization_history where id = 238

计数的结果是8,因为data->"$.row.*.code" returns ["J00.00", "V01.00", "G00.00", null, null, null, null, null];

如何在 json 数组中获取非空值的数量?

A from Akina 说到

Parse your array to the rowset then count non-null values. See https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=dd0a37bb25d526f029a7a82c6a1fe0cc

fiddle中的SQL是:

WITH cte AS (SELECT '["J00.00", "V01.00", "G00.00", null, null, null, null, null]' jstr)
SELECT COUNT(val)
FROM cte
JOIN JSON_TABLE(cte.jstr,
                '$[*]' COLUMNS (val VARCHAR(255) PATH '$')) jtable

结果

COUNT(val)
3

最后,找到 MySQL 8+ 的解决方案:

SELECT JSON_LENGTH(
    JSON_SEARCH('["J00.00", "V01.00", "G00.00", null, null, null]','all','%')
) AS count;

Try it here