views:

243

answers:

0

Hi,

I have an example table as below that I'm trying to do analyse upon, to learn using PHP and MYSQL for producing statistical results;

TableID | RNGResult | sessionseq | sessionid | Date | Scriptname
1       | 1         | 1          | 1
2       | 7         | 2          | 1
3       | 2         | 3          | 1
4       | 12        | 4          | 1
5       | 7         | 5          | 1
6       | 12        | 6          | 1
7       | 2         | 7          | 1
8       | 4         | 1          | 2
9       | 3         | 2          | 2
10      | 10        | 3          | 2

The RNGResult is generated by a PHP script to produce random numbers from 0 to 12, sessionseq is the order of the random results generated, and sessionid is exactly that the session or trial that the numbers were generated.

The table is indexed on "TableID", "RNGResult", "sessionseq" and "sessionid".

I would like to be able to calculate the difference between drawseq, where sessionid = X and RNGResult = Y, for instance for the table above, where selecting "sessionid=1 AND RNGResult=7" would return;

0
3

OR if we queried selecting "sessionid=1 AND RNGResult=2 AND RNGResult=7";

0
1
2
2

What i acheived in PHP is to load the results into an array, and perform analyse from there, which was fine at first but as we have generated more results - 20,000+, performance and memory issues have arrived, so think I should be able to do this from MYSQL.

I have tried the below two querys, both return the correct result, but are somewhat slow, yeilding transactions of between 40secs - 8minutes for a sequence of 20,000 results.

SELECT t1.`RNGResult`, t1.`sessionseq`, IFNULL((t1.`sessionseq` - 
(SELECT MAX(t2.`sessionseq`) FROM testtbl t2 WHERE (t2.`RNGResult` = 7) 
AND t2.`sessionseq` < t1.`sessionseq` AND t2.`sessionid` = 4)),0) AS diff FROM testtbl t1 
WHERE (t1.`RNGResult` = 7) AND t1.`sessionid` = 4;
SELECT t1.`RNGResult`, t1.`sessionseq`,IFNULL((t1.sessionseq - t2.sessionseq),0) as `diff`
FROM 
(SELECT `RNGResult`, `sessionseq` FROM testtbl WHERE `RNGResult` = 7 AND `sessionid` = 1) t1 
LEFT OUTER JOIN 
(SELECT `RNGResult`, `sessionseq` FROM testtbl WHERE `RNGResult` = 7 AND `sessionid` = 1) t2
ON t2.`sessionseq` = (SELECT MAX(`sessionseq`) FROM testtbl 
WHERE `sessionseq` < t1.`sessionseq` AND `RNGResult` = 7 AND `sessionid` = 1);

So am now somewhat lost, and am unsure if im heading in the right direction, any help would be appreciated, also bearing in mind that I may require further analyse being, COUNT, MEAN, MODE, STDDEV, etc of the final query results.

Thanks