I am trying to select rows from a JSON table column (in MySQL 5.7.3) that meet a certain condition. And yes, using a JSON column rather than just creating a separate MySQL table is intentional. Consider the following MySQL table:
Table: Record
CREATE TABLE Record (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
foo VARCHAR(3) DEFAULT 'bar',
data JSON DEFAULT NULL <--- WE POPULATE THIS COLUMN WITH DATA
)
Create a 'Record' with the following data
[{
"id": 1,
"timestamp": 1623671469
},
{
"id": 2,
"timestamp": 1623672921
},
{
"id": 3,
"timestamp": 1623872921
}]
Result
+---------------------------------------+
| Record [id,foo,data] |
+---------------------------------------+
| [1, 'bar', [{"id":1,"timestamp":162..]|
+---------------------------------------+
Now we want to select rows in the data column where id is larger than 2
SELECT
JSON_EXTRACT(data, "$[*].id") as result
FROM
Record
WHERE
JSON_EXTRACT(data, "$[*].id") > 2 <--- does not work, returns [1,2,3] for any number
Similarly, we want to be able to return the rows that have a timestamp between timestamp1 and timestamp2.
Is it possible to select only those rows that meet a condition using JSON_EXTRACT (in MySQL 5.7.3)?