I currently have this JSONs in my database
user | info |
---|---|
0 | ["subscriptions": [{"user": 1}, {"user": 2}]] |
1 | [] |
2 | null |
And I want something like
SELECT *
FROM user_info
WHERE count(subscriptions) == 2
(select by count of elements in "subscriptions" key of JSON)
I’ve tried with JSON_SEARCH, but didn’t managed to get something to work
2
Answers
I think your JSON format that you saved in DB is not proper JSON, Please validate the string in JSON validator online. Please check below screenshot
Correct JSON format should be
Based on the JSON format provided below is the sql query for your requirement
If above suggested format is not suitable for you, then use below:
Then your query will be:
When you use any JSON format, make sure it is a valid format by using json validators,
You can count the number of occurrences of the key user by getting the difference between the
CHAR_LENGTH
of the info column and theCHAR_LENGTH
of the info column (again) but this time, usingREPLACE
to replace any occurrence of user with theLENGTH
of user usingSPACE
. The difference will essentially be the occurrence count of the static value user.Result:
db<>fiddle here.
Otherwise, you need to fix your
JSON
formatting in your array column to use theJSON
functionality in MySQL.