如何计算逗号分隔列表 MySQL 中的项目

编程入门 行业动态 更新时间:2024-10-28 07:20:04
本文介绍了如何计算逗号分隔列表 MySQL 中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

所以我的问题很简单:

我在 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 中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-15 11:48:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/864995.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:逗号   项目   列表   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!