1

MySQL version: 5.7.29

I've a column layout_status with JSON datatype which contains array of values such as:

["Layouted"]
["Retired"]
["Verified"]
["Layouted", "Retired"]
["Layouted", "Verified"]

I want to select the records containing either "Layouted" or "Retired" or both.

I thought performing IN like SELECT * FROM users WHERE layout_status IN ('[\"Layouted\",\"Retired\"]'); would solve problem but it returns zero results.

Later I've tried with JSON_CONTAINS like below

SELECT * 
  FROM users
  WHERE ( JSON_CONTAINS(layout_status, "[\"Layouted\"]")
  OR      JSON_CONTAINS(layout_status, "[\"Retired\"]")
        )

But with the above query I get the records that has only either "Layouted" or "Retired". Records with ["Layouted", "Retired"] are ignored.

Is there any way to get all the records that contains "Layouted" or "Retired" or both?

1
  • Dquote chars are string-typed value delimiters, not a part of a value. Commented Jul 1, 2021 at 12:51

4 Answers 4

4

You need to use JSON_CONTAINS properly. You want to search for a string inside an array, not an array inside an array:

WHERE JSON_CONTAINS(layout_status, '"Layouted"')
OR    JSON_CONTAINS(layout_status, '"Retired"')

Demo on db<>fiddle

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

1 Comment

When I use this I get an error Error Code: 3141. Invalid JSON text in argument 2 to function json_contains: "Invalid value." at position 0.
0

Use JSON_CONTAINS already explained but if you want full query, then you can checkout this

SELECT * FROM `table_name` WHERE JSON_CONTAINS(column_name,'"value1"') 
AND JSON_CONTAINS(column_name, '"value2"');

Comments

0
select json_contains('["Layouted", "Retired"]', '["Layouted"]'), json_contains('["Layouted", "Retired"]', '["Retired", "Layouted"]'), json_contains('["Layouted", "Retired"]', '["Retired2", "Layouted"]')

Comments

0

You need to use JSON_OVERLAPS function, json_contains only search for a single value. but you want to select the records containing either "Layouted" or "Retired" or both.

WHERE JSON_OVERLAPS(layout_status, '["Layouted", "Retired"]')

Here second param for JSON_OVERLAPS is a json array, if you need search for another text, just add the text to this json array. You do not need to repeat JSON_OVERLAPS like in json_contains.

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.