Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql REGEXP to match two comma separated strings

Tags:

regex

mysql

I have a table containing following values :

id    |    value      |
-----------------------
1     | 1,2,5,8,12,20 |    
2     | 11,25,26,28   |    
-----------------------

now I want to search some comma separated IDs e.g. '1,3,6,7,11' from above value column e.g.

SELECT id FROM tbl_name  
WHERE value REGEXP '*some reg exp goes here containing 1,3,6,7,11*'
LIMIT 1,0;

SELECT id FROM tbl_name  
WHERE value REGEXP '*some reg exp goes here containing 3,6,27,15*'
LIMIT 1,0;

above 1st query should return 1 while the 2nd should return NULL

I am new with regular expressions can anyone help. Thanks

like image 271
prashant Avatar asked May 25 '13 06:05

prashant


People also ask

How do I compare two comma separated strings in SQL?

Use a split function (many examples here - CLR is going to be your best option in most cases back before SQL Server 2016 - now you should use STRING_SPLIT() ). Save this answer. Show activity on this post.

How do I find comma separated values in MySQL?

Search in a column containing comma-separated valuesMySQL has a dedicated function FIND_IN_SET() that returns field index if the value is found in a string containing comma-separated values. For example, the following statement returns one-based index of value C in string A,B,C,D .

What is Regexp_like in MySQL?

The REGEXP_LIKE() function in MySQL is used for pattern matching. It compares whether the given strings match a regular expression or not. It returns 1 if the strings match the regular expression and return 0 if no match is found.


1 Answers

REGEXP '(^|,)(1|3|6|7|11)(,|$)'

Will match all values containing one number of the sequence 1,3,6,7,11.

You should not use one column to save several values. Normalize data!

Edited answer

like image 177
Michel Feldheim Avatar answered Oct 29 '22 16:10

Michel Feldheim