goldlife goldlife - 1 year ago 107
SQL Question

MySQL 5.7 with native JSON support - how to select rows where a specific value exists in array?

I have a persons Table with a native JSON field / column called "json".
The first row of my table has this content in the column json:

{"misc": [{"sdsd": "sdsdsd"}], "size": 178, "social": {"skype": "4455454", "myspace": "fw2121ege", "twitter": "wr4541", "facebook": "frfsfsfasfsf"}, "mobility": ["forklift_sparkle", "license_for_passenger_transport", "car", "driver_license"], "piercing": true, "shoesize": 43, "trousers": {"width": 32, "length": 32}, "haircolor": "black", "shoe_size": 43, "additional_career": [{"ddgdgdg": "dggdgddg"}], "additional_social": [{"StudiVZ": "sfsfsfsf"}], "additional_language": [{"gfggfgf": "good"}], "additional_mobility": ["sfsf"]}

or here well formatted:

So - my question is: How can I search if the value "car" exists in the object "mobility"?

This does not work:

SELECT * FROM `Persons` WHERE JSON_EXTRACT(`persons`.`json`,"$.mobility[*]") = 'car'

(gives no result)

Also not work:

SELECT * FROM `Persons` WHERE JSON_SEARCH(`persons`.`json`, 'all', 'car', NULL, '$.mobility[*]')

(gives no result)

This (with JSON_CONTAINS) also does not work:

SELECT * FROM `Persons` WHERE JSON_CONTAINS(`persons`.`json`, 'car', "$.mobility")

(gives error: SELECT * FROM
, 'car', "$.mobility") )

BUT this works well:

SELECT * FROM `Persons` WHERE JSON_CONTAINS(`persons`.`json`, '178', "$.size")

I think it is a problem because "mobility" contains an array... but how to select if an element exists in this array "mobility" ?

Answer Source


FROM `Persons`
WHERE JSON_CONTAINS(`Persons`.`json`, '["car"]', '$.mobility');