To retrieve records from the part of a comma-separated list, you can use built in function FIND_IN_SET().
Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20), Marks varchar(200) ); Query OK, 0 rows affected (0.61 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Marks) values('Larry','98,34,56,89'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Name,Marks) values('Chris','67,87,92,99'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Name,Marks) values('Robert','33,45,69,92'); Query OK, 1 row affected (0.22 sec)
Following is the query to display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+-------------+ | Id | Name | Marks | +----+--------+-------------+ | 1 | Larry | 98,34,56,89 | | 2 | Chris | 67,87,92,99 | | 3 | Robert | 33,45,69,92 | +----+--------+-------------+ 3 rows in set (0.00 sec)
Following is the query to retrieve records from the part of a comma separated list. Here, we are getting the records of a student with marks 99 −
mysql> select Id,Name from DemoTable where find_in_set('99',Marks) > 0;
This will produce the following output −
+----+-------+ | Id | Name | +----+-------+ | 2 | Chris | +----+-------+ 1 row in set (0.00 sec)