I will divide logic into separate steps to facilitate.
First, let’s see where was the last occurrence of number 21, for example:
SELECT reg
FROM tabelaMaisOuMenosAssim
WHERE 21 IN (num0,num1,num2,num3,num4,num5)
ORDER BY reg DESC
LIMIT 1;
Once obtained this record, just count how many there are after it. In your example, we would have received 3
in return.
To know how many came after (one can use >=
if you want to include the current line):
SELECT COUNT(*) AS atrasado WHERE reg > 3
If you are using any auxiliary support language, this can be done with two darlings and use of variables.
Putting the two things together
We can make a subquery to obtain the result in a single operation:
SELECT COUNT(*) AS atrasado
FROM tabelaMaisOuMenosAssim
WHERE reg >= (
SELECT reg
FROM tabelaMaisOuMenosAssim
WHERE 21 IN (num0,num1,num2,num3,num4,num5)
ORDER BY reg DESC
LIMIT 1
);
See working on SQL Fiddle.
If you will constantly use this feature
You can create a FUNCTION
which is part of the database, rather than using the query every time you need to get a value:
CREATE FUNCTION pegaAtrasado(numero int)
RETURNS int
RETURN (
SELECT COUNT(*)
FROM tabelaMaisOuMenosAssim
WHERE reg >= (
SELECT reg
FROM tabelaMaisOuMenosAssim
WHERE numero IN (num0,num1,num2,num3,num4,num5)
ORDER BY reg DESC
LIMIT 1
)
);
How to use (simple as that):
SELECT pegaAtrasado( 21 );
SELECT pegaAtrasado( 5 );
SELECT pegaAtrasado( 1 );
See working on SQL Fiddle.
@The biggest advantage of direct FUNCTION in DB is that you will only need SELECT() in PHP, without running the query every time (Function is created directly in Mysql, and once, and remains there, is not done in PHP). The advantage of doing as you did is that it is easier to maintain, because you will only touch the PHP side, although it has less performance (the difference is usually small).
– Bacco
I’ve been analyzing the code but, this way I’m not able to perform the consultation of these late ones until a certain date. I’m doing so:
SELECT COUNT(*) AS atrasado FROM resultado_loteria WHERE codCadastro >= ( SELECT codCadastro FROM resultado_loteria WHERE codModalidade = 2 AND 1 IN (num0,num1,num2,num3,num4,num5,num6,num7,num8,num9,num10,num11,num12,num13,num14) AND dataConcurso BETWEEN '2015-01-01' AND '2015-11-03' ORDER BY codCadastro DESC LIMIT 1 )
. To show I’m using a "for" loop from 1 to 25 when I call the class.– Thiago