Organizational Research By

Surprising Reserch Topic

mysql check if numbers are in a comma separated list


mysql check if numbers are in a comma separated list  using -'mysql,list'

I have a table like this:

UID(int) NUMBERS(blob)
----------------------
1        1,13,15,20
2        3,10,15,20
3        3,15


And I would like to test if 3 and 15 are in the blob called NUMBERS. And can see the LIKE %% cannot be used

Only row with ID 2 and three scoulb be selected...
    

asked Sep 22, 2015 by ajit.chavhan
0 votes
69 views



Related Hot Questions

4 Answers

0 votes

This one also works:

SELECT * FROM table WHERE 3 IN (NUMBERS) AND 15 IN (NUMBERS)

using the IN will look into a comma separated string eg. these two

WHERE banana IN ('apple', 'banana', 'coconut')
WHERE 3 IN (2,3,6,8,90)

Info found on this page:

answered Sep 22, 2015 by deven.bendale
0 votes

Also check if this is helpful to anyone

An Extended function to eliminate the limitation of native FIND_IN_SET() in MySQL, this new extended version FIND_IN_SET_X() provides feature to compare one list with another list.

i.e.

mysql> SELECT FIND_IN_SET_X('x,c','a,b,c,d'); -> 3

Checkout this link for more details.

answered Sep 22, 2015 by virendra.bajaj
0 votes

Not the most pretty solution, but it works:

select
   UID
from
   YOUR_TABLE
where
   find_in_set('3', cast(NUMBERS as char)) > 0
   and
   find_in_set('15', cast(NUMBERS as char)) > 0

Note that it's string comparison, so you may need to cast your input parameters to char as well.

answered Sep 22, 2015 by deepak07.s
0 votes

find_in_set_x

create a new function in mysql and paste in the following (not my work by the way)

BEGIN
DECLARE limitCount INT DEFAULT 0;
DECLARE counter INT DEFAULT 0;
DECLARE res INT DEFAULT 0;
DECLARE temp TEXT;
SET limitCount = 1 + LENGTH(inputList) - LENGTH(REPLACE(inputList, ',',''));
simple_loop:LOOP
SET counter = counter + 1;
SET temp = SUBSTRING_INDEX(SUBSTRING_INDEX(inputList,',',counter),',',-1);
SET res = FIND_IN_SET(temp,targetList);
IF res > 0 THEN LEAVE simple_loop; END IF;
IF counter = limitCount THEN LEAVE simple_loop; END IF;
END LOOP simple_loop;
RETURN res;
END
answered Sep 22, 2015 by vijaygupta1980

...