2

Currently using MYSQL 5.7, soon to be migrating to 8.0. We have a json field in our database which has values which look like this:

[
  {
     "first_name":"bob",
     "last_name":"lisserman"
  },
  {
     "first_name":"bob",
     "last_name":"rippleman"
  },
  {
     "first_name":"joe",
     "last_name":"roterlam"
  }
]

I'm trying to write a query which finds records which contain an object in the array with both "first_name" = "bob" AND "last_name" = "rippleman"

Does JSON_CONTAINS support a search like this?

2
  • Which version of MySQL are you using? Commented Mar 2, 2020 at 14:49
  • @GMB - Added info on version in description. MYSQL 5.7 now, hoping to move to 8.0 soon. Commented Mar 3, 2020 at 3:38

1 Answer 1

2

12.17.3 Functions That Search JSON Values :: JSON_CONTAINS(target, candidate[, path]):

...

  • A candidate object is contained in a target object if and only if for each key in the candidate there is a key with the same name in the target and the value associated with the candidate key is contained in the value associated with the target key.

...

MySQL 5.7 and MySQL 8.0 try:

SELECT
  `id`,
  `json_field`
FROM
  `tbl_table`
WHERE
  JSON_CONTAINS(`json_field`, '{"first_name": "bob", "last_name": "rippleman"}');

See dbfiddle.

MySQL 8.0 try:

SELECT
  `tbl_table`.`id`,
  `tbl_table`.`json_field`
FROM
  `tbl_table`, JSON_TABLE(
    `json_field`,
    '$[*]'
    COLUMNS(
      `first_name` VARCHAR(50) PATH '$.first_name',
      `last_name` VARCHAR(50) PATH '$.last_name'
    )
) `der`
WHERE
  `der`.`first_name` = 'bob' AND
  `der`.`last_name` = 'rippleman';

See dbfiddle.

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

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.