1

I've a field that looks like this

1,13,15

If I try to make a search to find all rows than contains "1", then it's taking all rows that have 1 inside, and not only rows that says 1, [something], but also "11","13" etc.

I've tried with a like statement and wildcards, but without luck.

6
  • what is the dbms being used? Commented Oct 13, 2016 at 19:22
  • What you try so far ? LIKE ? Commented Oct 13, 2016 at 19:25
  • 2
    Instead of taking this at face value. I am curious what this field is for/of? What are these numbers for? Could there be a better database setup? Commented Oct 13, 2016 at 19:39
  • 2
    If you have a comma separated list in a DB column then you are doing it wrong. Commented Oct 13, 2016 at 19:40
  • 1
    Proper solution is to fix your table so you don't have CSV data in a field. Normalize and put those values into a child table, and then your problem is moot. Commented Oct 13, 2016 at 19:51

7 Answers 7

3

If you're using MySQL, use FIND_IN_SET, not LIKE.

WHERE FIND_IN_SET('1', columnname)

But the best solution is to normalize your schema so you don't have comma-separated values in a column.

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

Comments

1

If you are using MySQL you can use regexp to check such values

where column_name regexp '^1,|,1,|,1$|^1$'

Comments

1

When you say "1*" it finds everything that has a one and anything after that. Just narrow down your search and serach for:

 field LIKE "1,%" OR field LIKE "%,1,%" OR field LIKE "%,1" OR field = "1"

2 Comments

what happen if 1 is on the middle?
what happen if text field is just '1' no more elements so no ','?
0

You can search for "1," OR "1" OR ", 1".

Comments

0

if your field is '1,13,15' change it to ',1,13,15,'

and your search to LIKE '%,1,%'

So depending on your db you should try something like this

 SELECT  * 
 FROM yourTable
 WHERE ','  + yourField + ',' LIKE  '%,' + @search + ',%'

Comments

0

Have you tried:

select rows
from table
where field contains '1,'

?

3 Comments

Sorry--not what I typed at the end.
Select row from table where left(field,2) = '1,'
Are the results always sorted nicely like you indicate, or could they be out of order, like '3,2,1,11' ?
0

If you're using MS SQL Server, you should use LIKE '%1%'.

Comments

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.