0

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?

fred00
  • 571
  • 2
  • 8
  • 23
  • 2
    Upgrade your server to 8+ version and use JSON_TABLE(). – Akina Jan 21 '22 at 14:24
  • Out of curiosity, why are you using JSON if it makes this simple query so difficult? Why not store the array as rows of a second table? Then the query would be easy. – Bill Karwin Jan 21 '22 at 16:17
  • 1
    This database is used to extract some reports. The original database is quite complex and takes too much to generate simple reports. I used this idea and worked pretty well in simple JSONs, but for this specific one I faced this problem. Unfortunately, I'm unable to upgrade to 8+, so I'll probably store these arrays as rows on a second table as you said. – fred00 Jan 21 '22 at 16:35

0 Answers0