I'm using MySQL 5.7 and I have a simple table with two columns: id
and json
. And I want to filter rows using objects inside an array within json
column.
Here's an example of a json
content:
{
"id": 12,
"items": [{
"price": 5,
"item": {
"name": "Item One"
}
},
{
"price": 10,
"item": {
"name": "Item Two"
}
}
]
}
I want to filter based on items.price
and items.item.name
.
I was able to filter using JSON_CONTENTS like this:
SELECT * FROM table WHERE JSON_CONTAINS(json, '{"price": 5}', '$.items')
AND
SELECT * FROM table WHERE JSON_CONTAINS(json, '{"item": {"name": "Item One"}}', '$.items')
However this only works when I'm looking for price EQUALS 5
and name EQUALS "Item One"
.
I need to find, for instance, price IS GREATER THAN 1
and I was not able to do so. I tried this:
SELECT * FROM table WHERE json->"$.items.price" > 1
But it doesn't work. When I use the where clause like this json->"$.items[0].price" > 1
it works, but it only consider the first array position.
I even tried this json->"$.items[*].price" > 1
but it returns an empty result.
I'm considering create another table, only with the items
. But if there is a way to filter the original table would be much simpler.
Does anyone have an idea?