I have this table for a web panel that I'm making:
On a particular page, the latest archive for each server is shown, which means it has to look at distinct server IDs and sort them by a descending time stamp as shown.
At the moment I'm having to run SELECT DISTINCT server_id FROM archives ORDER BY time DESC
but this means I have to use foreach
in PHP to run an additional query to get the rest of the fields for the archive (id, job_id, time, sha1_sum, file_name, size
).
Is there a single SQL statement that can get the latest archive of each server_id
sorted by time
descending? Doing it all in one query would be much easier and cleaner code-wise.
EDIT: I should note that the list of results in the web table are wrong, as the result from 15/06/2013 is displayed at the top when the archive directly below is more recent.
You could use GROUP BY and MAX in combination.
SELECT server_id,MAX(time), id, job_id, time, sha1_sum, file_name, size FROM archives GROUP BY server_id
This is yet another variation of the "max in group" problem, by far the most common problem SQL newbies seem to have.
One way to solve it is with a correlated subquery to identify all archives that have the maximum time in their respective group.
SELECT
a.server_id,
a.id, a.job_id, a.time, a.sha1_sum, a.file_name, a.size
FROM
archives a
WHERE
NOT EXISTS (
SELECT 1
FROM archives
WHERE server_id = a.server_id AND time > a.time
)
ORDER BY
time DESC
Index (server_id, time)
and do a GROUP BY on the outer query if you expect some archives for the same server_id
to have the same time
value.