0

So i have in my database a column = foo_ids and its content is as follows:
[{"id": "432"}, {"id": "433"}]

question is what query will give me back as a result all of the id's in this field?

out of several attempts my last one was
SELECT JSON_EXTRACT(foo_ids,'$.id') FROM foo_table but clearly it didn't work...any idea?

4
  • What version of MySQL are you running? Commented Aug 14, 2017 at 9:21
  • mysql Ver 14.14 Distrib 5.5.44, for debian-linux-gnu (x86_64) using readline 6.3 Commented Aug 14, 2017 at 9:25
  • Unless otherwise indicated, the JSON functions were added in MySQL 5.7.8., see 12.16 JSON Functions. Commented Aug 14, 2017 at 9:46
  • the solution @83N suggested worked for me Commented Aug 14, 2017 at 9:57

1 Answer 1

7

If you just want to return an array of the ID's you could do this:

SELECT JSON_EXTRACT(foo_ids, '$**.id') FROM foo_table;

The * wildcard evaluates each json object in an array.

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

3 Comments

Is there a way to return the array where id = 432 for example?
Yes, by doing something along the lines of SELECT JSON_EXTRACT(foo_ids, '$**.id') FROM foo_table WHERE JSON_CONTAINS(foo_ids, '{ "id" : "432" }'); - check out the MySQL docs here
This only works where the id is a string and not an int as such. '{ "id" : "432" }' will work but '{ "id" : 432 }' won't as it returns all items

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.