I am trying to query a Mysql json column that contains an array of objects. I want the length of the array where a condition is met in the objects
Example of the JSON array:
[
{"userId": 100, "type": 1, "status": 1},
{"userId": 101, "type": 2, "status": 1},
]
Current Query:
SELECT IFNULL(JSON_LENGTH(json_users), 0) AS my_count, post_id
FROM posts WHERE post_id = 6421028173277829027
AND json_contains(json_users, '{"type" : 1, "status": 1}');
This will return the following whic is desired
+------------+---------------------+
| my_count | post_id |
+------------+---------------------+
| 1 | 6421028173277829027 |
+------------+---------------------+
But if I change the query where param 'type' to say 3
SELECT IFNULL(JSON_LENGTH(json_users), 0) AS my_count, post_id
FROM posts WHERE post_id = 6421028173277829027
AND json_contains(json_users, '{"type" : 3, "status": 1}');
I get an empty set. But I'm trying to get the following:
+------------+---------------------+
| my_count | post_id |
+------------+---------------------+
| 0 | 6421028173277829027 |
+------------+---------------------+
I assume I have to change the where clause and somehow check inside the following:
IFNULL(JSON_LENGTH(## json_users ##), 0)
but I don't know where to start
EDIT:
The following query returns an array of paths to the objects so I can use JSON_LENGTH to get the count:
SELECT JSON_LENGTH(IFNULL(JSON_SEARCH(json_users->>'$[*].type', 'all', 1), JSON_ARRAY())) AS my_count
FROM posts WHERE post_id = 6421028173277829027;
In MySQL, the JSON_LENGTH() function returns the length of a JSON document. When you call this function, you provide the JSON document as an argument. You can also provide a path argument to return the length of a value within the document.
How to Retrieve data from JSON column in MySQL. MySQL provides two operators ( -> and ->> ) to extract data from JSON columns. ->> will get the string value while -> will fetch value without quotes. As you can see ->> returns output as quoted strings, while -> returns values as they are.
The drawback? If your JSON has multiple fields with the same key, only one of them, the last one, will be retained. The other drawback is that MySQL doesn't support indexing JSON columns, which means that searching through your JSON documents could result in a full table scan.
We can use the JSON_EXTRACT function to extract data from a JSON field. The basic syntax is: JSON_EXTRACT(json_doc, path) For a JSON array, the path is specified with $[index] , where the index starts from 0: mysql> SELECT JSON_EXTRACT('[10, 20, 30, 40]', '$[0]'); +------------------------------------------+
Did you try
SELECT JSON_LENGTH(JSON_EXTRACT(json_users, "$.type")) FROM posts
I know there is a bug where if json_users
is null, it will not return anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With