1

我想用下表中的相应 REVID 检索每个 NID 的最后一个“版本”:

+------+-------+-----+---------+----------+
| RHID | REVID | NID | VERSION |  ACTION  |
+------+-------+-----+---------+----------+ 
| 1    |   1   |  1  |    1    |  CREATE  |
+------+-------+-----+---------+----------+  
| 2    |   2   |  2  |    1    |  CREATE  |
+------+-------+-----+---------+----------+  
| 3    |   3   |  1  |    2    |  UPDATE  |
+------+-------+-----+---------+----------+  
| 4    |   4   |  1  |    3    |  UPDATE  |
+------+-------+-----+---------+----------+  
| 16   |   3   |  1  |    4    | ROLLBACK |
+------+-------+-----+---------+----------+

当我运行时:

SELECT a.nid, a.revID, MAX(a.version)
FROM `revision_history` a
GROUP BY a.nid; 

我希望结果是:

+-----+-------+---------+
| NID | REVID | VERSION |
+-----+-------+---------+
|  1  |   3   |    4    |
+-----+-------+---------+
|  2  |   2   |    1    |
+-----+-------+---------+

相反,结果是:

+-----+-------+---------+
| NID | REVID | VERSION |
+-----+-------+---------+
|  1  |   3   |    4    |
+-----+-------+---------+
|  2  |   2   |    4    |
+-----+-------+---------+

问:获得预期结果的适当查询是什么?

笔记:

这是为了构建一个视图(在 MySQL 中,它不支持子查询)。

4

2 回答 2

2

试试这个:

select a.nid ,a.revID ,a.version
from   `revision_history` a
JOIN
      (SELECT nid,  MAX(version) as version
        FROM `revision_history` 
        GROUP BY nid)b
ON    a.nid=b.nid
AND   a.version=b.version

SQL小提琴演示

于 2012-11-22T12:42:19.787 回答
1

我总是喜欢假设GROUP BY取第一个值FROM

SELECT nid ,revID ,version
FROM (  SELECT nid, revID, version
        FROM `revision_history`
        ORDER BY version DESC) AS h
GROUP BY nid

如果您知道行为并且永远不会超过1个案例,则该方法非常简短,易于理解和编辑。如果您出于某种原因在同一版本上有 2 个相同的版本nid,则结果可能是错误的。

于 2012-11-22T12:50:30.000 回答