3

I have a field ('roles') with this values

        roles
row_1: 1,2,3,5
row_2: 2,13

I do this:

SELECT * FROM bloques WHERE 2 IN (roles)

and only find row_2, because it starts by 2

The LIKE option doesn't work because if I find 1

SELECT * FROM bloques WHERE roles LIKE '%1%'

, it gives me both rows.

3
  • What is your requirement? I cant follow.. What value you expect? And why?
    – nawfal
    Dec 19, 2012 at 14:26
  • 3
    Don't mind all the answers below, the only valid answer is: Read up on database normalization and trash your database design!
    – fancyPants
    Dec 19, 2012 at 14:37
  • duplicate stackoverflow.com/questions/13928538/…
    – Sir Rufo
    Dec 19, 2012 at 14:42

5 Answers 5

3

FIND_IN_SET function cal helps you:

SELECT FIND_IN_SET('b','a,b,c,d');

For your code:

SELECT * FROM bloques WHERE FIND_IN_SET(2,roles);

Also, I suggesto to you that move your schema to 1NF

0
0

Could you use REGEXP? http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Otherwise, you could add commas to the front and end of your rows.

select * from mytable where ',' + roles + ',' like '%,2,%'
0
SELECT 
  * 
FROM 
  bloques 
WHERE 
  roles LIKE '%,2,%' 
  OR roles LIKE '2,%' 
  OR roles LIKE '%,2'

The first case will give you all cases where 2 is in the middle of a set, the second case is when 2 starts the set, and the third case is when 2 ends the set. This is probably terribly inefficient, but it should work.

1
  • ... and you need fourth case for '2' alone. There's a better way to do it.
    – raina77ow
    Dec 19, 2012 at 14:37
0

You can use this regex here:

SELECT * FROM bloques 
  WHERE roles REGEXP '[[:<:]]2[[:>:]]';

... or, in more generic case:

SELECT * FROM bloques 
  WHERE roles REGEXP CONCAT('[[:<:]]', :your_value, '[[:>:]]');

You need to use these weird-looking things, as they match word boundaries - preventing match for '2' to occur at '23' and '32'. )

The problem is that query is only the beginning of the troubles caused by using denormalized field. I'd suggest using either SET type (if the number of options is limited and low) or, way better, junction table to store the m-n relationships.

0

Use FIND_IN_SET() function

Try this:

SELECT * FROM bloques WHERE FIND_IN_SET(1, roles);

OR

SELECT * FROM bloques 
WHERE CONCAT(',', roles, ',') LIKE '%,1,%';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.