您可以使用MySQL的CHAR_LENGTH()方法对逗号分隔的字段中的值进行计数。语法如下-
SELECT *, (CHAR_LENGTH(yourColumnName) - CHAR_LENGTH(REPLACE(yourColumnName, ',','')) + 1) as anyVariableName from yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table CountValuesCommaSeparated -> ( -> Id int NOT NULL AUTO_INCREMENT, -> CommaSeparatedValue text, -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue) values('101,104,1900,46675,7895'); mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue) values('1010,18949,37465'); mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue) values('2010,1201,2743874,7485'); mysql> insert into CountValuesCommaSeparated(CommaSeparatedValue) values('4757,457587,48586,378575,3874765,487565');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from CountValuesCommaSeparated;
以下是输出-
+----+-----------------------------------------+ | Id | CommaSeparatedValue | +----+-----------------------------------------+ | 1 | 101,104,1900,46675,7895 | | 2 | 1010,18949,37465 | | 3 | 2010,1201,2743874,7485 | | 4 | 4757,457587,48586,378575,3874765,487565 | +----+-----------------------------------------+ 4 rows in set (0.00 sec)
这是查询以逗号分隔的字段中的值的查询:
mysql> select *, -> (CHAR_LENGTH(CommaSeparatedValue) - CHAR_LENGTH(REPLACE(CommaSeparatedValue, ',', '')) + 1) as TotalValue -> from CountValuesCommaSeparated;
以下是输出-
+----+-----------------------------------------+------------+ | Id | CommaSeparatedValue | TotalValue | +----+-----------------------------------------+------------+ | 1 | 101,104,1900,46675,7895 | 5 | | 2 | 1010,18949,37465 | 3 | | 3 | 2010,1201,2743874,7485 | 4 | | 4 | 4757,457587,48586,378575,3874765,487565 | 6 | +----+-----------------------------------------+------------+ 4 rows in set (0.00 sec)