MySQL db query to fetch records from comma separate values on the basis of a specific value

MySQLMySQLi Database

For this, you can use REGEXP in MySQL. Let’s say you want the row records wherein any of the comma separated value is 90. For this, use regular expression.

Let us first create a table −

mysql> create table DemoTable1447
   -> (
   -> Value varchar(100)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1447 values('19,58,90,56');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1447 values('56,89,99,100');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1447 values('75,76,65,90');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1447 values('101,54,57,59');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1447;

This will produce the following output −

+--------------+
| Value        |
+--------------+
| 19,58,90,56  |
| 56,89,99,100 |
| 75,76,65,90  |
| 101,54,57,59 |
+--------------+
4 rows in set (0.00 sec)

Following is the query to fetch records from comma separated values based on a specific value i.e. 90 here −

mysql> select * from DemoTable1447 where Value regexp '(^|,)90($|,)';

This will produce the following output −

+-------------+
| Value       |
+-------------+
| 19,58,90,56 |
| 75,76,65,90 |
+-------------+
2 rows in set (0.00 sec)
raja
Published on 10-Dec-2019 10:16:25
Advertisements