1

I wonder if this query is possible using json query.

I need to select all records that have more than 3 values a like. for example, I have an array [1,2,3,4,5,6].

Database record has:

# ["1","2","3","9","4","2"]     selected <--- this contains 1,2,3
# ["4","5","6","10","11","12"]  selected <--- this contains 4,5,6
# ["1","2","3","4","20","21"]   selected <--- this contains 1,2,3,4
4. ["1","2","21","22","23","24"]   not selected <-- only contains 1,2`

I was trying this query

select * from `combinations` where json_contains(`combination`, '"0"') and json_contains(`combination`, '"1"') and json_contains(`combination`, '"3"')
3
  • You are looking if value are lower than 7? Also, what is the issue with your query? Commented Apr 19, 2023 at 9:03
  • im looking for records that contain any of this array [1,2,3,4,5,6] but i need 3 or more must be present. for example, 5,3,1 should be in the field or 2,1,6. Commented Apr 19, 2023 at 9:07
  • I made an answer. Check it then don't forget to accept it with the check mark on the top left of it :) Commented Apr 19, 2023 at 11:34

2 Answers 2

0

As you did, you should use json method from mysql. You need to use JSON_TABLE (require mysql 8.0+).

By doing (here with last line of your example)

SELECT *
FROM
    JSON_TABLE('["1","2","21","22","23","24"]', "$[*]" COLUMNS(myId INT PATH "$")) a

You will have this table:

myId
1
2
21
22
23
24

After getting this, you should count for values with COUNT(*) and a WHERE clause that filter. I'm using the IN case as you have a small amount of possible value, but feel free to use < for example.

Final query with everything:

SELECT
    (SELECT count(*)
        FROM JSON_TABLE(t.json, "$[*]" COLUMNS(myId INT PATH "$")) a
        WHERE myId IN (1, 2, 3, 4, 5, 6)
    ) as amount, json
FROM
    test t

Result:

amount json
5 ["1","2","3","9","4","2"]
3 ["4","5","6","10","11","12"]
4 ["1","2","3","4","20","21"]
2 ["1","2","21","22","23","24"]

You can find example at DB fiddle.

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

Comments

0

This can be done by splitting the array into rows using json_table then check if arrays contains more than 2 elements from (1,2,3,4,5,6) :

I used distinct to count elements only ones, you can remove it if you want to count duplicates

with cte as (
  select distinct t.myjson, j.combination
  from combinations t
  join json_table(
    t.myjson,
    '$[*]' columns (combination varchar(50) path '$')
  ) j
)
select myjson, count(*)
from cte
where combination in (1,2,3,4,5,6)
group by myjson
having count(*) > 2

Demo here

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.