I can get the results that I need, but I need a fast query.
id value1 fid
1000 1203 5
1001 1293 1
1002 1203 3
1003 1211 1
1004 1263 1
1005 1223 5
1006 1243 2
1007 123 5
1008 1049 2
1009 1205 3
Here are the results that I need:
fid id value1 id2 previous_value1
1 1004 1263 1003 1211
2 1008 1049 1006 1243
3 1009 1205 1002 1203
5 1007 123 1005 1223
Any ideas?
Edit: I forgot to wrote my query here is my query:
SELECT
t1.fid,
t1.id,
t1.value1,
t2.id AS id2,
t2.value1 AS previous_value1
FROM
(
SELECT
MAX(id) AS id
FROM TABLENAME
GROUP BY fid
) t3
INNER JOIN TABLENAME t1 ON t1.id = t3.id
INNER JOIN TABLENAME t2 ON t2.id = (SELECT id FROM TABLENAME WHERE id < t1.id AND fid = t1.fid ORDER BY id DESC LIMIT 1)
Actually I simplified it by removing extra columns.
(There is 2 more columns in WHERE statement but it doesn’t matters.)
The original query takes ~0.04seconds. If I filter the results with the other two columns in where statement, it takes ~0.001 seconds.
Ok, here is a query that returns what you want (at least, what I think you want), but its anything but fast and efficient, so try it first: