Home >Database >Mysql Tutorial >How to Count Items in Comma-Separated Strings in MySQL?

How to Count Items in Comma-Separated Strings in MySQL?

Linda Hamilton
Linda HamiltonOriginal
2025-01-04 20:19:40415browse

How to Count Items in Comma-Separated Strings in MySQL?

Counting Items in Comma Separated Strings in MySQL

You need to determine the number of items in a comma-separated column in your MySQL database. To achieve this, you can utilize the following technique:

By calculating the difference between the length of the original string and the length of the string without commas, you can obtain the count of items:

LENGTH(fooCommaDelimColumn) - LENGTH(REPLACE(fooCommaDelimColumn, ',', ''))

This expression takes into account the trailing comma in the string, so you won't need to add an additional 1. For strings that do not have a trailing comma, you can add 1 to the expression:

LENGTH(col) - LENGTH(REPLACE(col, ',', '')) + 1

This approach utilizes the built-in LENGTH and REPLACE functions to accomplish the task without utilizing external functions or custom code.

The above is the detailed content of How to Count Items in Comma-Separated Strings in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn