MySQL query to fetch specific records matched from an array (comma separated values)

MySQLMySQLi Database

To fetch records from comma separated values, use MySQL FIND_IN_SET(). Let us first create a table −

mysql> create table DemoTable1548
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> ArrayListOfMarks varchar(100)
   -> );
Query OK, 0 rows affected (0.88 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('Chris','56,78,90,87');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('Bob','90,78,65');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('David','91,34,56,78,87');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1548;

This will produce the following output −

+-----------+-------------+------------------+
| StudentId | StudentName | ArrayListOfMarks |
+-----------+-------------+------------------+
|         1 | Chris       |    56,78,90,87   |
|         2 | Bob         |       90,78,65   |
|         3 | David       | 91,34,56,78,87   |
+-----------+-------------+------------------+
3 rows in set (0.00 sec)

Here is the query to fetch specific records matching from comma separated values −

mysql> select * from DemoTable1548 where find_in_set('87',ArrayListOfMarks);

This will produce the following output −

+-----------+-------------+------------------+
| StudentId | StudentName | ArrayListOfMarks |
+-----------+-------------+------------------+
|         1 | Chris       |    56,78,90,87   |
|         3 | David       | 91,34,56,78,87   |
+-----------+-------------+------------------+
2 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 10:45:21
Advertisements