gpt4 book ai didi

MYSQL - 计算是否以逗号分隔的项目

转载 作者:行者123 更新时间:2023-11-29 10:44:41 27 4
gpt4 key购买 nike

我有一个tinytext字段,它可以包含3个不同的值,格式如下:

  • “X”或“Y”(其中 X 和 Y 可以是任意数字)
  • “A,B,C,D”(其中 A、B、C 和 D 可以是任意数字)

我想查询表并计算用逗号分隔或不用逗号分隔的项目数。

例如这些行:

  • 42
  • 42,56,99
  • 24,10090

那么预期计数将为 6。

我找不到正确的查询。

最佳答案

好的,这是测试数据:

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() 忽略 NULL。

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,这会更容易.

关于MYSQL - 计算是否以逗号分隔的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44832660/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com