How to count items in comma separated list MySQL(如何计算逗号分隔列表 MySQL 中的项目)
问题描述
所以我的问题很简单:
我在 SQL 中有一个列,它是一个逗号分隔的列表(即 cats,dogs,cows,
)我需要使用 only 来计算其中的项目数sql(所以无论我的函数是什么(暂时称之为 fx)都可以这样工作:
I have a column in SQL which is a comma separated list (ie cats,dogs,cows,
) I need to count the number of items in it using only sql (so whatever my function is (lets call it fx for now) would work like this:
SELECT fx(fooCommaDelimColumn) AS listCount FROM table WHERE id=...
我知道这是有缺陷的,但你明白了(顺便说一句,如果 fooCommaDelimColumn
的值是 cats,dogs,cows,
,那么 listCount 应该返回 4...).
I know that that is flawed, but you get the idea (BTW if the value of fooCommaDelimColumn
is cats,dogs,cows,
, then listCount should return 4...).
仅此而已.
推荐答案
没有内置函数可以统计字符串中子字符串出现的次数,但是可以计算原始字符串与相同字符串的差值,不用逗号:
There is no built-in function that counts occurences of substring in a string, but you can calculate the difference between the original string, and the same string without commas:
LENGTH(fooCommaDelimColumn) - LENGTH(REPLACE(fooCommaDelimColumn, ',', ''))
它在将近 8 年的时间里被编辑了多次(哇!),所以为了清楚起见:上面的查询不需要 +1
,因为 OPs 数据有一个额外的尾随逗号.
It was edited multiple times over the course of almost 8 years now (wow!), so for sake of clarity: the query above does not need a + 1
, because OPs data has an extra trailing comma.
虽然实际上,对于看起来像这样的字符串的一般情况:foo,bar,baz
正确的表达式是
While indeed, in general case for the string that looks like this: foo,bar,baz
the correct expression would be
LENGTH(col) - LENGTH(REPLACE(col, ',', '')) + 1
这篇关于如何计算逗号分隔列表 MySQL 中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何计算逗号分隔列表 MySQL 中的项目


- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01