如何统计从 MySQL 数据库中检索的行中逗号分隔的特定值?


要统计逗号分隔的值,请将聚合函数 COUNT(*) 与 FIND_IN_SET() 一起使用。我们先创建一个表 -

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

使用 insert 命令在表中插入一些记录 -

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)

使用 select 语句显示表中的所有记录 -

mysql> select *from DemoTable;

这将产生以下输出 -

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

以下是从数据库中检索逗号分隔值的查询 -

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

这将产生以下输出 -

+----------+
| count(*) |
+----------+
|        3 |
+----------+
1 row in set (0.00 sec)

更新于:04-Oct-2019

413 次浏览

开启你的职业生涯

完成课程获得认证

开始吧
广告
© . All rights reserved.