Mysql extract json data and search multiple values

Viewed 4025

Hi I have car listing website and I want to filter multiple values from a JSON column data

My database table looks like this:

id | label    | data
---|----------|---------------------------------
 1 | "test 1" | {"Year":"2014","Gear":"Auto"}
 2 | "test 2" | {"Year":"2010","Gear":"Manual"}
 3 | "test 3" | {"Year":"2009","Gear":"None"}

For example I want to filter by Gear, either "Auto" or "Manual":

SELECT * FROM test WHERE 
JSON_EXTRACT(data, "$.Year") in (2010,2014) AND
JSON_EXTRACT(data, "$.Gear") in ("Auto","Manual")

The query returns zero results when I add the filter for Gear, but the filter for Year works fine.

2 Answers

I would recommend json operator ->>, which combines JSON_EXTRACT() and JSON_UNQUOTE():

select * 
from test
where data ->> '$.Year' in (2010, 2014) and data ->> '$.Gear' in ('Manual', 'Auto');

->> was added in MySQL 5.7.13.

Related