3

I have the following json array in my column:

[  
   {  
      "day": 1,
      "requests": 23
   },
   {  
      "day": 2,
      "requests": 5
   },
   {  
      "day": 2,
      "requests": 9
   }
]

and I want the row that has day 1. I already tried to do it with

SELECT * FROM api WHERE usages->'$[*].day' = JSON_ARRAY(1)

but it returns no results.

4
  • 3
    Try dbfiddle. Commented Sep 1, 2018 at 17:07
  • 2
    @wchiquito You should post it as answer Commented Sep 1, 2018 at 17:12
  • Thanks @LukaszSzozda, but Schwern's answer includes my proposal. Commented Sep 2, 2018 at 7:09
  • @wchiquito At point where I wrote that answer Schwern's answer was deleted. You could check it using stackoverflow.com/posts/52130389/revisions. Anyway good job and keep going :) Commented Sep 2, 2018 at 10:25

1 Answer 1

3

select usages->'$[*].day' from api shows that it's the JSON array [1,2,2].

where usages->'$[*].day' = JSON_ARRAY(1) is trying to match [1,2,2] with [1] which isn't true.

Instead, use JSON_CONTAINS to look for values within the array.

where json_contains(usages->'$[*].day', "1");

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

2 Comments

How is [1,2,2] equal to 1? where usages->'$[*].day' = 1. This query returns 0 rows. Counterexample demo
@LukaszSzozda Whoops. Had to install MySQL to remember how their JSON works.

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.