P
P
PendalF892019-02-05 16:50:36
MySQL
PendalF89, 2019-02-05 16:50:36

How to query a nested json array in MySQL?

Hello!
There is a json that is written in the data_json field with type "json" in a MySQL table:

{
  "name": "Test",
  "books": [
    {
      "id": 1
    },
    {
      "id": 2
    }
  ]
}

How can I select by the id of the books array, where id = 1?
I tried something like this, but it doesn't work like this:
SELECT
  * 
FROM
  test
WHERE
  data_json -> "$.books[*].id" = 1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaliy Orlov, 2019-02-05
@orlov0562

Not at all, or I don't know how.
The fact is that the selection data_json -> "$.books[*].id" will return such a value "[1, 2]" it is incorrect to compare it with a number.
MySQL 8 has JSON_TABLE , I assume that from "[1, 2]" you can make a table and build a condition on it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question