0

I realise the title of this question may scream "duplicate" but I don't think it is (at least if it is, I haven't seen it).

I am currently storing a list separated by commas in the database like 1,3,5,6,13 but when I do SELECT id FROM users WHERE additional_usergroups LIKE '%3%' both 3 and 13 show up.

Is there a way round this?

EDIT
I'm looking for only 3 to show up in the result, sorry for being so vague with the question.

Thanks.

3
  • 1
    Yes - properly normalize your database. (Or use FIND_IN_SET, if you want to keep the mess you have right now at any cost ...) Commented Aug 22, 2017 at 13:45
  • you want exact 3 in your result? Commented Aug 22, 2017 at 13:46
  • Yes, I only want 3 to show up, @a_a Commented Aug 22, 2017 at 13:47

2 Answers 2

5

This is why RDBMS have normalization guidelines. I encourage you to read about normalization and why values in databases should be singular.

But, a way around this would be including every possibility of just 3:

additional_usergroups LIKE '3' 
OR additional_usergroups LIKE '%,3,%'
OR additional_usergroups LIKE '3,%'
OR additional_usergroups LIKE '%,3'

As @CBroe pointed out, MySQL appears to have a FIND_IN_SET function to handle this:

WHERE FIND_IN_SET('3', additional_usergroups) > 0

However, normalization is still recommended for a RDBMS.

Sign up to request clarification or add additional context in comments.

Comments

-3
SELECT id FROM users WHERE additional_usergroups LIKE '3%'

the '%' means grab whatever you can which is why its used for search features so frequently. if you remove it you will only grab numbers that begin with 3, so 3,31,312 etc.

5 Comments

Thanks @Cody but this still wouldn't be useful to me because if I was to have 31 it would pickup that and I wouldn't want it.
if you just want the '3' then get rid of both '%'. like '3'
@Cody Then you won't find anything, since the value of the field is "3,1,2,31,4" and not just "3".
SQL would pull the entire row no matter what right? I dont understand how you would be just getting the 3,13
You should use a string split to and put the comma separated values inside a temporary table and that will resolve your problem

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.