Let’s say we have a table with columns DAY and NUMERO.
There can be numerous rows with the same value of DAY but NUMERO is always unique.
What could be the most efficient way to get the item immediately preceding an existing couple (DAY, NUMERO) in a list ordered by DAY, NUMERO ?
I precise that I need this for mysql and I don’t want to add a specific index (that’s the reason why I don’t simply use a linear function of DAY and NUMERO).
Here’s an ordered test case :
DAY | NUMERO
1 | 11
1 | 12
1 | 15
4 | 7
4 | 9
4 | 14
5 | 8
6 | 10
6 | 19
My request must do this :
(1,11) => nothing
(1,15) => (1,12)
(4,7) => (1,15)
(4,9) => (4,7)
(4,14) => (4,9)
EDIT :
my current best solution is to have two successive queries :
select * from item where day=? and numero<? order by day desc, numero desc limit 1;
select * from item where day<? order by day desc, numero desc limit 1;
If the first query gives a result, I don’t have to run the second one.
A similar solution would be to use a union but mysql doesn’t seem to authorize unions with more than one column.
Both solutions look too heavy for a problem seeming so simple…
If you are only retrieving the previous pair based on a single pair as opposed to trying to do the entire table, as others have alluded to, you could try the following simple query –