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"')
2
Answers
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)
You will have this table:
After getting this, you should count for values with
COUNT(*)
and aWHERE
clause that filter. I’m using theIN
case as you have a small amount of possible value, but feel free to use<
for example.Final query with everything:
Result:
You can find example at DB fiddle.
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 duplicatesDemo here