Anita
Anita

Reputation: 117

mysql query to find rows with 5 or more consecutive records in a range

I have a situation where i have to identify 5 or more consecutive records in the first 10 records. I have given 2 examples below:

Example 1 as follows

SL  User       Number   Frequency
1   aaa         9.95    1
2   aaa         9.85    1
3   aaa         9.75    1
4   aaa         9.65    1
5   aaa         9.55    1
6   aaa         9.45    1
7   xxxx        9.35    1
8   bbbb        9.25    1
9   cccc        9.15    1

I want a query that can pick up records 5 & 6 (Numbers 9.55 and 9.45 that belong to user aaa and update the frequency as 2 instead of 1).

Example 2 as follows

SL  User    Number  Frequency
1   xxxx     9.95   1
2   aaa      9.85   1
3   aaa      9.75   1
4   aaa      9.65   1
5   aaa      9.55   1
6   aaa      9.45   1
7   xxxx     9.35   1
8   bbbb     9.25   1
9   cccc     9.15   1

The query should pick up only record 6 (Number 9.45 that belong to user aaa and update frequency to 2 instead of 1).

The query should pick up records where 5 or more consecutive records appear anywhere in top 9 positions of a user and mark the frequency as 2 for positions after the 4th position.

Constraints: This query is executed every 2 seconds via an ajax in a php. So i really don't want a complex join / union query that uses lot of cpu. I have the option of doing this in php, by breaking up into 2 or more smaller queries, but prefer a single query that does not load the cpu or database. If a single query is likely to load the cpu i'm ok with 2-3 queries as processing happens in php.

Can you please advise how to this can be achieved ?

Upvotes: 0

Views: 376

Answers (1)

Moe Tsao
Moe Tsao

Reputation: 1054

if it is only the first 10 records, PHP solution should not be THAT consuming..

$arr= mysql result arrays;
$old_user="";
$count=0;
foreach ($arr as $a){
    if ($a['name']==$old_user){
       $count++;
    }else{
       $count=0;
    }
    if ($count > 4) {
        // run the update query here

    }
    $old_user=$a['name'];
}

See if it works for your need.

Upvotes: 1

Related Questions