How to count specific comma separated values in a row retrieved from MySQL database?

MySQLMySQLi Database

To count comma-separated-values, use aggregate function COUNT(*) along with FIND_IN_SET(). Let us first create a table −

mysql> create table DemoTable
(
   Value varchar(100)
);
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('10,20,60,80');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('60,70,90');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('50,55,65,60');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('90,98,97');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+
| Value       |
+-------------+
| 10,20,60,80 |
| 60,70,90    |
| 50,55,65,60 |
| 90,98,97    |
+-------------+
4 rows in set (0.00 sec)

Following is the query to count comma-separated values retrieved from the database −

mysql> select count(*) from DemoTable
   where find_in_set('60',Value) > 0;

This will produce the following output −

+----------+
| count(*) |
+----------+
|        3 |
+----------+
1 row in set (0.00 sec)
raja
Published on 04-Oct-2019 06:37:38
Advertisements