views:

49

answers:

5

Hello, I know it is not an appropriate technique to have a structure of MySQL table as such, but I have to work with such. The problem is, that the field in table has value with comma seperated integers, like "1,3,5,7,10" and I want the query to return rows, in which field has a to the query passed number in it, like:

SELECT * FROM `table` WHERE '5' IN (`field_in_table`)

However, it does not work, if, in this case, '5' is not the first number in the field. Any advises, how to solve that?

Thanks in advance, Regards, Jonas

+1  A: 

You could use WHERE field_in_table LIKE '%5%' instead. Of course, the problem would be, '1,59,98' would return as wel.

Joachim VR
It won't work, because it will return it either it will be 50 or 5 :S
flyeris
Better make that '%,5,%' if you're looking for '5' only and not '25' or '51' too.
Filburt
+1  A: 
SELECT * FROM table WHERE field_in_table LIKE '%5'");

should work

Tokk
+1  A: 

You could try

SELECT *
    FROM table
    WHERE '%,5,%' LIKE field_in_table OR
          '%,5'   LIKE field_in_table OR
          '5,%'   LIKE field_in_table;

A better approach might be to use regular expressions, a subject on which I am not an authority.

Brian Hooper
+4  A: 

Have a look at

FIND_IN_SET

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string.

astander
Thanks - this is the functionality, which I was looking for. I simplyg forgot this command :)
flyeris
A: 
SELECT * 
FROM table 
WHERE FIELD LIKE '%,5,%' OR 
      FIELD LIKE '5,%' OR 
      FIELD LIKE '%,5'
codaddict