Reputation: 24
My table contains some columns with ;-separated numbers like this :
1;2;43;22;20;12
and so on. It's also possible there's only 1 number in this column like 110
, or 2 numbers like this 110;143
I want to select the rows that contain a certain number in this column. The number is in a variable $search_var. Let's say I need to search for the number 1 in my column. If I use a select with like statement like so :
"SELECT * FROM Table WHERE ids LIKE '%".$search_var."%'"
I get all results containing '1' and not only '1', so I also get 11, 14, 110, 1999 etc. I think I need to use some sort of regex-statement but I'm lost here... Who can help ?
Upvotes: 0
Views: 177
Reputation: 12255
You might not need regex for this
Set @YourNUmber := 110;
SELECT *
FROM Table
WHERE ';' + ids + ';' LIKE '%;'+ @yourNumber + ';%'
This guarantees there are always ;
surrounding all the numbers.
This is formatted for SQL Server. The variable syntax and wildcards might be different if you are using something else.
EDIT:
Thanks @FélixGagnon-Grenier for the suggestions. I think either of these two will work. See here for a SQL Fiddle example
SELECT *
FROM T
WHERE concat(';',ids,';') LIKE concat('%;', @YourNumber , ';%');
SELECT *
FROM T
WHERE LOCATE(concat(';', @YourNumber , ';'),concat(';',ids,';'))>0
Upvotes: 2
Reputation: 3681
Try this solution if you're using SQL Server. This searches for the number where adjcent characters are not numbers:
SELECT * FROM Table WHERE ids LIKE '%[^0-9]".$search_var."[^0-9]%'
Upvotes: 0