1

I have a table and in one column I have weekdays as JSON data. I'm trying a query to get results if it has one or more than one day that matches the user selection.

My Table:

CREATE TABLE test (id SERIAL, label VARCHAR(16), data VARCHAR(80));

INSERT INTO test VALUES
    (null, 'test 1', '["Monday", "Tuesday", "Friday"]'),
    (null, 'test 2', '["Thursday", "Friday"]'),
    (null, 'test 3', '["Sunday", "Saturday", "Monday"]');

My Query:

SELECT * FROM test
WHERE JSON_UNQUOTE(JSON_EXTRACT(data, '$[*]')) IN ('Monday', 'Tuesday');

The query was supposed to give me test 1 and test 2 as result.

Here is the DB Fiddle.

1 Answer 1

1

You can use OR to do it

SELECT * FROM test
where JSON_CONTAINS(data,'"Monday"')=1 or JSON_CONTAINS(data,'"Tuesday"')

Working demo

If you do not want to use OR,then you can try json-overlaps like below:

   SELECT * FROM test WHERE 
      JSON_OVERLAPS(data,'["Monday","Tuesday"]')=1

But be careful that it only support starting with MySQL 8.0.17

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

8 Comments

These days will be entered by the user. This way I need to add OR dynamically in the query. Any other option?
@Omer you can use json-overlaps to do it
json-overlaps only display one result. SELECT * FROM test WHERE JSON_CONTAINS(data,'["Monday","Tuesday"]')=1
its not working on DB Fiddle - db-fiddle.com/f/fC48mHEM1nuLUZCTP8CLfs/45
@Omer see the last part of my answer,But be careful that it only support starting with MySQL 8.0.17
|

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.