1

Let's assume this users table:

-----------------------------------------
| id | ... | info                       |
-----------------------------------------
| 1  | ... | {"items":["132","136"]}    |

I need to make a request to fetch users that have items with id == 136.
This following is the sql I built but it does not work and I dont understand why:

SELECT _u.id FROM users _u WHERE _u.info REGEXP '("items":)([)("136")(])'

Thank you in advance!

3
  • try SELECT _u.id FROM users _u WHERE _u.info like '"136"' Commented Jul 22, 2020 at 6:19
  • Why don't you use myaql's json functions instead? Commented Jul 22, 2020 at 6:19
  • @maha It might work but considering accuracy... Commented Jul 22, 2020 at 6:54

1 Answer 1

2

Here is one approach using the MySQL JSON functions:

SELECT *
FROM yourTable
WHERE JSON_SEARCH(JSON_EXTRACT(json, "$.items"), 'one', "136") IS NOT NULL;

Demo

The call to JSON_EXTRACT first extracts the JSON array under the items key. Then, we use JSON_SEARCH to try to find an element "136".

Edit:

If you are certain that the JSON to be searched would always just be one key items along with a single level JSON array, then REGEXP might be viable here:

SELECT *
FROM yourTable
WHERE json REGEXP '"items":\\[.*"136".*\\]';

Demo

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

6 Comments

Mysql has thrown this error: FUNCTION dev.JSON_SEARCH does not exist
What is your MySQL version? If you're using a very old version, then it may not have full JSON support. In that case, and assuming you expect a need to work with JSON, then consider upgrading to MySQL 8+.
5.0.12 in local but even my prod hosting has thrown the same error.
It is running in the demo, this is all I can observe here.
@dovstone OK I have given you an option using REGEXP, but note carefully that in general searching JSON content using regular expression is generally a very bad idea. If your JSON to search is anything other than what you showed us, REGEXP could backfire and return false positives.
|

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.