Today there was a question on the Freenode MySQL channel about a
classical problem: Rows holding group-wise maximum of a column.
This is a problem that I keep encountering every so often, so I
thought I would write up something about it.
A good example of the problem is a table like the following
holding versioned objects:
CREATE TABLE object_versions (
object_id INT NOT NULL,
version INT NOT NULL,
data VARCHAR(1000),
PRIMARY KEY(object_id, version)
) ENGINE=InnoDB
Now it is easy to get the latest version for an object:
SELECT data FROM object_versions WHERE object_id = ? ORDER BY version DESC LIMIT 1
The query will even be very fast as it can use the index to
directly fetch the right row:
mysql> EXPLAIN SELECT data FROM object_versions
WHERE object_id = 42 ORDER BY version DESC …
[Read more]