Reputation: 2604
I have this query
select json_length(data->"$.row.*.code") as count from hospitalization_history where id = 238
The result in count is 8, because data->"$.row.*.code"
returns ["J00.00", "V01.00", "G00.00", null, null, null, null, null]
;
How can I a get number of not null values in json array?
Upvotes: 2
Views: 1602
Reputation: 2604
Finally, found this solution for MySQL 8+:
SELECT JSON_LENGTH(
JSON_SEARCH('["J00.00", "V01.00", "G00.00", null, null, null]','all','%')
) AS count;
Upvotes: 2
Reputation: 3166
Parse your array to the rowset then count non-null values. See https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=dd0a37bb25d526f029a7a82c6a1fe0cc
The SQL in the fiddle is:
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
Results in
COUNT(val) |
---|
3 |
Upvotes: 1