MySQL query to select a row which contains same number in a column with set of numbers separated by comma?


You need to use FIND_IN_SET() for this. Let us first create a table −

mysql> create table DemoTable
   (
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(20),
   CustomerAllProductPrice text
   );
Query OK, 0 rows affected (0.30 sec)

Insert some records in the table using insert command. Here, we are inserting numbers separated by comma −

mysql> insert into DemoTable(CustomerName,CustomerAllProductPrice) values('Chris','245,345,678,90,45,56,78');
Query OK, 1 row affected (0.03 sec)

mysql> insert into DemoTable(CustomerName,CustomerAllProductPrice) values('Chris','98,99,90,56,77');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(CustomerName,CustomerAllProductPrice) values('David','1000,2000,4000,56000');
Query OK, 1 row affected (0.06 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------+--------------+-------------------------+
| CustomerId | CustomerName | CustomerAllProductPrice |
+------------+--------------+-------------------------+
|          1 | Chris        | 245,345,678,90,45,56,78 |
|          2 | Chris        | 98,99,90,56,77          |
|          3 | David        | 1000,2000,4000,56000    |
+------------+--------------+-------------------------+
3 rows in set (0.00 sec)

Following is the query to select a row which contains same number in column with set of numbers separated by comma −

mysql> select *from DemoTable where find_in_set('4000',CustomerAllProductPrice);

This will produce the following output −

+------------+--------------+-------------------------+
| CustomerId | CustomerName | CustomerAllProductPrice |
+------------+--------------+-------------------------+
|          3 | David        | 1000,2000,4000,56000    |
+------------+--------------+-------------------------+
1 row in set (0.14 sec)

Updated on: 30-Jul-2019

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements