I have a MySql table with a text field.
The text field would be populated with a random sequence similar to this (could be any integer values though):
14,4,24,20,34,2
34,67,4,98,64
No leading or trailing comma on the string (text field value).
I would like to do a count on total occurrences of only ‘4’ for example.
Query on these two rows should return a count of 2 and not 7.
Not positive how a query like this would be formulated.
thanks
2
Answers
Here is what I got working, and seems to give the correct result:
select count(*) as total_blocks from poll_info where poll_blocks like '%,4,%' OR poll_blocks like '4,%' OR poll_blocks like '%,4'
I will do some further testing and hopefully this will solve the issue, thanks for your time in this.
For MySQL 8.X
You can make use of
REGEXP_REPLACE
to find the 4, remove them from the string and compute the difference of length:That returns the number of "4" per row, then you can sum it all up:
You might also want to rename these values with
AS
.Explanation of the Regex
(?<=^|,)4(?=$|,)
is looking for "4" which match these conditions:For older MySQL versions
The query is quite ugly, but you can use the following:
What it does is first replace all the occurrences of "4" as an element (so not in 54 for example) with underscores (
_
).Then, it computes the length of the string with these underscores minus the length of the string without the underscores, and that’s the number of "4"s in your list.
Why so many
REPLACE
?During testing the query, I’ve discovered that MySQL
REPLACE
functions doesn’t behave as we would expect. With this example:4,4,4,4,4
, if using a single Replace, we would expect it to return_,_,_,_,_
. However, it does the replace in-place, and if a comma is "matched" twice, it won’t count the second time, hence why 2REPLACE(..., ",4,", ",_,")
.