9

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.

4
  • 1
    I dont see a question or a description of a problem here! Commented Dec 6, 2020 at 18:54
  • JSON_EXTRACT(data, "$.Gear") in ("Automatic","Manuel") this code not working Commented Dec 6, 2020 at 19:09
  • You need to describe your goal in detail before we can help you figure out where you're going wrong. Commented Dec 6, 2020 at 19:18
  • Of course sorry my english, i have json data from mysql column, when i select checkbox "Automatic" and "Manual" i want listing all this records Commented Dec 6, 2020 at 19:43

2 Answers 2

11

JSON_EXTRACT returns a JSON string, which includes quotation marks. You can either include this in your search:

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

Or use the JSON_UNQUOTE function:

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

See fiddle here: https://www.db-fiddle.com/f/fC48mHEM1nuLUZCTP8CLfs/0

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you!! I'm really happy right now, its working! really thank you again!
Happy to help, welcome to Stack Overflow.
This not work from array json ["2010","2014", ...] :(
@JorhelReyes get the same issue, you found something else?
4

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.

2 Comments

Nice one, I knew about the -> operator but not ->>
Warning: this method with operators "->" and "->>" not work in MariaDB 10.7. It's only work with MySQL at this moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.