问题描述
所以我的问题很简单:
我在 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 中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)