1

First of all, I am not sure if my title explains this question in the correct way but I think my code will.

Instead of doing this:

SELECT * FROM mytable WHERE JSON_EXTRACT(`cars`,'$."65"') = 'Toyota' OR JSON_EXTRACT(`cars `,'$."66"') = 'Toyota' OR JSON_EXTRACT(`cars `,'$."67"') = 'Toyota' 

I want to do this:

SELECT * FROM mytable WHERE JSON_EXTRACT(`cars`,any of these 65,66,67) = 'Toyota'

Can this be done?

2
  • Provide table structure and example data.. Place it on sqlfiddle.com.. Then we can help you. Commented May 28, 2018 at 11:19
  • JSON_EXTRACT(json_doc, path[, path] ...) source dev.mysql.com/doc/refman/8.0/en/… .. Looks like it's possible to include multiple paths.. Commented May 28, 2018 at 11:22

1 Answer 1

6

According to the documentation, you may pass any number of paths as arguments 2 onward to the JSON_EXTRACT function. So the following should work:

SELECT *
FROM yourTable
WHERE JSON_UNQUOTE(JSON_EXTRACT(`cars`, '$."65"', '$."66"', '$."67"')) LIKE '%"Toyota"%';

Demo

Note that the WHERE clause will actually return string values in the form ["some_value"], hence I compare against this. Someone with more experience with MySQL's JSON API can probably do better than what I wrote above. But, this does at least partially answer your question; yes, you can extract multiple paths in a single call to JSON_EXTRACT.

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

9 Comments

Slightly wondering why OP needs to be told again today though ... stackoverflow.com/q/50528364/1427878
@CBroe I'm part of the problem; I haven't tested this yet...I'm setting up a query now.
This question is little bit different.. Because JSON_EXTRACT() with multiple paths returns a JSON ARRAY..Guess he should not figure it out on how to match that with the string Toyota @CBroe ... TimBiegeleisen answer looks like it's solving that problem
"Someone with more experience with MySQL's JSON API can probably do better than what I wrote above" MySQL JSON API is a bit bit i would expect JSON_UNQUOTE(JSON_EXTRACT(cars, '$."65"', '$."66"', '$."67"')) = JSON_ARRAY("Toyota") would also select rextester.com/UXF29788.. Your query might be the best solution.
Tim, your solution is pretty close to what I want. The only thing I don't want is the LIKE at the end. I tried to use = instead but that gives me no rows.
|

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.