问题:
I have this table for documents (simplified version here): 我有此表用于文档(此处为简化版):
+------+-------+--------------------------------------+
| id | rev | content |
+------+-------+--------------------------------------+
| 1 | 1 | ... |
| 2 | 1 | ... |
| 1 | 2 | ... |
| 1 | 3 | ... |
+------+-------+--------------------------------------+
How do I select one row per id and only the greatest rev? 如何为每个ID选择一行,而仅选择最大转速?
With the above data, the result should contain two rows: [1, 3, ...]
and [2, 1, ..]
. 根据上述数据,结果应包含两行: [1, 3, ...]
和[2, 1, ..]
。 I'm using MySQL . 我正在使用MySQL 。
Currently I use checks in the while
loop to detect and over-write old revs from the resultset. 目前,我在while
循环中使用检查功能来检测并覆盖结果集中的旧版本。 But is this the only method to achieve the result? 但这是获得结果的唯一方法吗? Isn't there a SQL solution? 没有SQL解决方案吗?
Update 更新资料
As the answers suggest, there is a SQL solution, and here a sqlfiddle demo . 作为答案提示, 有一个SQL的解决方案,并且这里sqlfiddle演示 。
Update 2 更新2
I noticed after adding the above sqlfiddle , the rate at which the question is upvoted has surpassed the upvote rate of the answers. 在添加上述sqlfiddle之后 ,我注意到问题被投票的速率已经超过答案的投票率。 That has not been the intention! 那不是意图! The fiddle is based on the answers, especially the accepted answer. 小提琴基于答案,尤其是已接受的答案。
解决方案:
参考一: https://stackoom.com/question/WUzB/SQL仅选择列上具有最大值的行-重复参考二: https://oldbug.net/q/WUzB/SQL-select-only-rows-with-max-value-on-a-column-duplicate
来源:oschina
链接:https://my.oschina.net/u/4438370/blog/4311412