Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Where like statement

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.

like image 474
Flexer Avatar asked Dec 04 '22 19:12

Flexer


2 Answers

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?

like image 178
Bill Karwin Avatar answered Dec 07 '22 23:12

Bill Karwin


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,%';
like image 44
Savas Vedova Avatar answered Dec 08 '22 00:12

Savas Vedova