Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible with one MySQL query? "column contains any of the array's values"

Basically I want to check whether a mysql text column, which contains comma-separated values, contains any of the values contained in an array. I know this can be done with a loop and multiple queries, but I was hoping for a single query. Is this possible? Thank you.

like image 728
Rob Avatar asked Oct 26 '25 08:10

Rob


2 Answers

I would use a solution like this:

SELECT
  *
FROM
  yourtable
WHERE
  str RLIKE
  CONCAT('[[:<:]]', REPLACE('values,in,the,array', ',', '[[:>:]]|[[:<:]]'), '[[:>:]]')

this will make the following string:

'values,in,the,array'

like this:

[[:<:]]values[[:>:]]|[[:<:]]in[[:>:]]|[[:<:]]the[[:>:]]|[[:<:]]array[[:>:]]

[[:<:]] and [[:>:]] are word boundaries so it will match only whole words, and | is an OR so it will match any of the words. Please see fiddle here.

like image 180
fthiella Avatar answered Oct 28 '25 21:10

fthiella


Do you mean

... WHERE my_column LIKE '%first_array_value%' OR my_column LIKE '%second_array_value%'

It will work but very bad because of performance. There is also another way

... WHERE MATCH (my_column) AGAINST ('first_array_value second_array_value')

but the best way is to change data structure if possible.

like image 24
zelibobla Avatar answered Oct 28 '25 21:10

zelibobla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!