You need a GROUP BY
clause with the aggregate MAX()
. MySQL permits you to omit it (where other RDBMS would report errors) but with indeterminate results, which you are seeing. This can be handled by joining against a subquery which returns the grouped rev
per id
.
SELECT
r.id,
r.state,
maxrev.rev
FROM
VIEW_data r
/* INNER JOIN against subquery which returns MAX(rev) per id only */
JOIN (
SELECT id, MAX(rev) AS rev
FROM VIEW_data GROUP BY id
/* JOIN is on both id and rev to pull the correct value for state */
) maxrev ON r.id = maxrev.id AND r.rev = maxrev.rev
WHERE r.id = 1
http://sqlfiddle.com/#!2/4f651/8
The above will return the max rev
value for any id
. If you are certain you only need the one row as filtered by the WHERE
clause rather than the MAX()
per group, look at the other answer which makes use of ORDER BY
& LIMIT
.