Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql - count values from comma-separated field

Tags:

mysql

count

I have to do some statics from read-only db where value are stored in a weird form

example: I have 2 rows like

ID    text field 
1     1001,1003,1004 
2     1003, 1005

I need to be able to count that this is "5".

I don't have write access so don't know how to read and count right away without creation a function or something like that.

like image 505
annvio Avatar asked Jan 31 '13 20:01

annvio


People also ask

How do I count comma separated values in MySQL?

SQL Pattern: How can I count the number of comma separated values in a string? Basically, you replace all occurrences of , with an empty string "" , then subtract its LENGTH from the LENGTH of the unadulterated string, which gives you the number of , characters.

How split comma separated values in SQL query?

Split comma-separated value string in a column. SELECT ProductId, Name, value FROM Product CROSS APPLY STRING_SPLIT(Tags, ','); Here is the result set. The order of the output may vary as the order is not guaranteed to match the order of the substrings in the input string.


1 Answers

Clever solution here on SO: How to count items in comma separated list MySQL

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

EDIT

Yes you can select it as an additional column: and correcting with the CHAR_LENGTH from @HamletHakobyan's answer:

SELECT 
  ID, 
  textfield, 
  (CHAR_LENGTH(textfield) - CHAR_LENGTH(REPLACE(textfield, ',', '')) + 1) as total 
FROM table
like image 75
Matthew Avatar answered Sep 30 '22 10:09

Matthew