To check if value exists in a comma separated list, you can use FIND_IN_SET() function.
The syntax is as follows
SELECT *FROM yourTablename WHERE FIND_IN_SET(‘yourValue’,yourColumnName) > 0;
Let us first create a table. The query to create a table is as follows
mysql> create table existInCommaSeparatedList - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > Name varchar(200) - > ); Query OK, 0 rows affected (0.68 sec)
Now you can insert some records in the table using insert command.
The query is as follows
mysql> insert into existInCommaSeparatedList(Name) values('John,Carol,Sam,Larry,Bob,David'); Query OK, 1 row affected (0.35 sec) mysql> insert into existInCommaSeparatedList(Name) values('Maxwell,Chris,James'); Query OK, 1 row affected (0.14 sec) mysql> insert into existInCommaSeparatedList(Name) values('Robert,Ramit'); Query OK, 1 row affected (0.34 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from existInCommaSeparatedList;
The following is the output
+----+--------------------------------+ | Id | Name | +----+--------------------------------+ | 1 | John,Carol,Sam,Larry,Bob,David | | 2 | Maxwell,Chris,James | | 3 | Robert,Ramit | +----+--------------------------------+ 3 rows in set (0.00 sec)
Here is the query to check if value exists in a comma separated list. We are checking for the field with comma separated text “Robert”
mysql> SELECT *FROM existInCommaSeparatedList WHERE FIND_IN_SET('Robert',Name) > 0;
The following is the output
+----+--------------+ | Id | Name | +----+--------------+ | 3 | Robert,Ramit | +----+--------------+ 1 row in set (0.00 sec)