php + mysql count consecutive data

Posted on 16th Feb 2014 by admin

I have a database of values and I want to work out how to display them if the values match a consecutive pattern.

For example, I might have the table "eggs" with the values "1", "2", "3", "4", "6", "7", "8", "9", "10". Now if I were to count these up I'd have 9 total values, this is good. What I want to do is ONLY count the values where they have another 2 consecutive values after them. So for example if the above pattern is what I'm using and I want to check for 2 consecutive values, the following would happen:

1 -> correct, it is followed by "2" and "3".
2 -> correct, it is followed by "3" and "4".
3 -> false, it is followed by "4" but no "5"
4 -> false, it is followed by "6", no"5".
6 -> correct, followed by "7" and "8".
7 -> correct, followed by "8" and "9".
8 -> correct, followed by "9" and "10".
9 -> false, followed by "10" but no "11".

and this would return the total of 7, because 7 of these values are followed by 2 consecutive numbers, therefore are correct.

So my question: How would I go about this? Would it be a matter of a single (albeit complex) mysql query or will I have to do some more advanced stuff after fetching the array? If it's the second I can do that myself, but I'd like to (hopefully) do it in a query!

So, any ideas?

Other forums