我有一个tinytext字段,它可以包含3个不同的值,格式如下:
我想查询该表,并计算用逗号分隔或不分隔的项目数。
例如,使用这些行:
那么预期的计数将是6。
我找不到正确的查询。
发布于 2017-06-29 18:52:06
好的,这是测试数据:
mysql> create table t (f tinytext);
mysql> insert into t values ('42'), (null), ('42,56,99'), ('24,10090');
mysql> select * from t;
+----------+
| f |
+----------+
| 42 |
| NULL |
| 42,56,99 |
| 24,10090 |
+----------+您可以计算字符串中有多少个数字,作为字符串长度的差异和去掉逗号的字符串(对于列表中的第一个数字添加1)。
mysql> select f, length(f), length(replace(f,',','')), 1+ length(f)-length(replace(f,',','')) from t;
+----------+-----------+---------------------------+----------------------------------------+
| f | length(f) | length(replace(f,',','')) | 1+ length(f)-length(replace(f,',','')) |
+----------+-----------+---------------------------+----------------------------------------+
| 42 | 2 | 2 | 1 |
| NULL | NULL | NULL | NULL |
| 42,56,99 | 8 | 6 | 3 |
| 24,10090 | 8 | 7 | 2 |
+----------+-----------+---------------------------+----------------------------------------+然后使用SUM()来得到总数。SUM()忽略NULLs。
mysql> select sum(1+length(f)-length(replace(f,',',''))) from t;
+--------------------------------------------+
| sum(1+length(f)-length(replace(f,',',''))) |
+--------------------------------------------+
| 6 |
+--------------------------------------------+如果您使用don't store comma-separated lists in a string,这会更容易。
https://stackoverflow.com/questions/44832660
复制相似问题