1

how to use WHERE in an array of JSON data in MYSQL

I have a simple table myTable having one column with JSON datatype.

create table myTable(profile JSON default NULL);

then I inserted this record

insert into myTable values ('[{"name":"","type":"student","age":""},
{"name":"","type":"teacher","age":"240"},
{"name":"","type":"student","age":"25"},
{"name":"","type":"student","age":"20"}]')

my question is I want to retrieve all records names who are a student and age between 20 & 25?

is it possible to use it like this? SELECT name FROM myTable WHERE type = "student' and age BETWEEN 20 &2 5

1
  • 3
    Would it be possible to create a normal database table, using name, type and age as columns, instead of putting this in one column using a JSON string? Commented Mar 16, 2022 at 8:57

2 Answers 2

2
SELECT jsontable.name, jsontable.age 
FROM myTable
CROSS JOIN JSON_TABLE(myTable.profile,
                      '$[*]' COLUMNS (name VARCHAR(255) PATH '$.name',
                                      `type` VARCHAR(255) PATH '$.type', 
                                      age INT PATH '$.age')) jsontable
WHERE jsontable.`type` = 'student'
  AND jsontable.age BETWEEN 20 AND 25;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=559ea1476f933a7ac977537e434f3206

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

3 Comments

I would call this a very good illustration of why using JSON data in MySQL is a bad idea.
@KIKOSoftware i think that using JSON (CSV, XML and so on) is bad idea in any DBMS when there are any operations except save and retrieve with this value. It contradicts normal forms in most cases.
I agree completely.
0

There is a complete chapter on JSON functions, and how they can be used.

select * 
from (
   select 
      x.x, 
      json_unquote(json_extract(profile,concat("$[",x.x,"].name"))) as name, 
      json_unquote(json_extract(profile,concat("$[",x.x,"].type"))) as type, 
      json_unquote(json_extract(profile,concat("$[",x.x,"].age")))  as age
   from myTable
   cross join (select 0 as x union select 1 union select 2 union select 3 union select 4) x
) t 
where t.type='student' and t.age between 20 and 25;

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.