1

I'm trying all sort of possibilities to extract a single element in a JSON column that contains an array. Let me give the example:

Database:
id | info
---------
1  |{"name": "aaa", "colors": ["a","b"]}
2  |{"name": "bbb", "colors": ["c","d"]}
3  |{"name": "ccc", "colors": ["e","f"]}

What I need is to have a similar query, like: select name, color from info where color = a;

And this should return: "aaa", "a"

The problem that I'm stuck is that I cannot search in the array without a fix index, but I need to be able to query the database without fix index.

2
  • Consider to use a relational design, when you use a relational database system. Commented Jun 16, 2020 at 12:57
  • And this should return: "aaa", "a" What is the point of output a well-known literal "a" that is used as the filtering condition? Commented Jun 16, 2020 at 17:30

2 Answers 2

1
SELECT info->"$.name" AS `name`
FROM test
WHERE JSON_CONTAINS(info, '"a"', '$.colors');
Sign up to request clarification or add additional context in comments.

Comments

1

You can use json_search():

select info ->> '$.name' as name, 'a' color
from mytable 
where json_search(info ->> '$.colors', 'one', 'a') is not null

Comments

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.