F
F
freeeeez2016-09-15 18:49:47
Laravel
freeeeez, 2016-09-15 18:49:47

How to search for a substring from an array in a database?

There is an array(2,3,4)
There is a column in the database that can contain such values ​​as "2", "2.3", "2.4", "2,3,4", etc.
How to write a search condition like whereIn(numbers,array(2,3,4)) only to search as a LIKE %...% construct?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
X
xmoonlight, 2016-09-15
@freeeeez

Bitmask: 1,2,4,8,16,32,64,.... sum of digits - will give the bitmask of the desired option.
Let there be an array: array(2,3,4) or array("mom","soap","frame") - it doesn't matter!
It is important that it has a maximum of 3 elements.
Then we make a bit mask for all 3 items:
1+2+4=7 (which is in binary form: 111)
I.e. if there are 7 in the DB field, then we know that all 3 values ​​are selected.
1+0+4=5 (which is in binary form: 101)
I.e. if there is 5 in the DB field, then we know that the first and last value is selected,
and so on.

I
Ilya, 2016-09-15
@glebovgin

If not more than 9, then you can use REGEX?
First, of course, you need to do implode('|', $array);
If the numbers are greater than 9, then you need to think.

T
ThunderCat, 2016-09-15
@ThunderCat

I understand that "the task is such and we solve it as best we can", but ideally, you need to spread such values ​​​​into a separate table with a many-to-many relationship, because like is not the fastest command, even in the expression like ...%, about like %..% generally silent. And so - solid perversions like `numbers` like %2% and `numbers` like %3% and so on until the end, I am silent about problems with numbers over 9, where you need to define 12 or 1.2.

M
maximw, 2016-09-15
@maximw

Convert field to SET type .
In queries use FIND_IN_SET()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question