4

I have a table with two columns (id, numberslist).

How can I get all rows that have exactly "1" in numberslist (in this case id = 2)

Whats the sql statement?


id | numberslist

1 | 11,111
2 | 1,2,3


This doesnt work:

$sql = "SELECT * FROM mytabelle WHERE numberslist LIKE '%1%'";

I know it's a bad database design to list all numbers in this way but its not changeable.

Flexer
  • 131
  • 2
  • 7

4 Answers4

7

MySQL supports "word boundary" patterns in its regular expression syntax for this purpose.

WHERE numberlist REGEXP '[[:<:]]1[[:>:]]'

You could alternatively use FIND_IN_SET():

WHERE FIND_IN_SET('1', numberlist) > 0

That said, I agree with comments in other answers that storing a comma-separated list in a string like this is not good database design. See my answer to Is storing a comma separated list in a database column really that bad?

Community
  • 1
  • 1
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • +1 thanks for the into to the Find_In_Set function. Sadly, I'm going to find that useful. – dash Dec 09 '11 at 00:20
  • This answer summarizes why Bill has 94k points and I have only 763 points :D +1 for the nice answer, I totally forgot about regex and FIND_IN_SET – Savas Vedova Dec 09 '11 at 00:24
  • Nice find, Bill. To the OP -- long as you stay in MySQL, this is a good solution. :) – Joe Dec 09 '11 at 01:11
4

The design is really bad. Anyways, for this bad design, this bad code should do the work :D

SELECT * FROM mytabelle WHERE numberslist = '1' OR
                              numberslist LIKE '%,1' OR 
                              numberslist LIKE '%,1,%' OR 
                              numberslist LIKE '1,%';
Savas Vedova
  • 5,622
  • 2
  • 28
  • 44
3

For this specific case, you could do something like:

WHERE numberslist = '1' OR numberslist LIKE '1,%' OR numberslist LIKE '%,1,%' OR numberslist LIKE %,1'";

assuming there's no whitespace between numbers and commas.

But that's ugly, not to mention will be unable to use any kind of indexing at all.

Joe
  • 41,484
  • 20
  • 104
  • 125
2

You should read about table normalization. Here's a good introduction.

Ignas
  • 1,965
  • 2
  • 17
  • 44