Hello:
I have a table with a very simple schema:
CREATE TABLE q(
orig INTEGER NOT NULL,
dest INTEGER NOT NULL,
cost FLOAT,
PRIMARY KEY (orig, dest)
);
I need to walk that table backwards in a cost minimizing way. Let me explain.
I need a tour of 15 points, a point can be an orig
or a dest
. My algorithm is a backtracking from the last dest
to the initial orig
. So here is how I spell it out:
Given the final
dest
, find theorig
which would link to saiddest
with minimumcost
. The correspondingorig
becomes the newdest
; loop over this 15 times.
Let's assume that I know the last dest
is number 10
. The SQL statement that allows me to find the orig
leading to a dest
in a cost-
minimizing way is:
SELECT orig FROM q WHERE cost = (SELECT MIN(cost) FROM q WHERE dest = 10);
Now I would use the orig
returned by the above function to find the previous point (assume it returned, say, point 5
):
SELECT orig FROM q WHERE cost = (SELECT MIN(cost) FROM q WHERE dest = 5);
I can go on like this until I have the 15 points.
How to make an efficient query to do this in SQL? My table has 50 million rows.