我想使用下表中相应的REVID为每个NID检索最后一个“VERSION”:
+------+-------+-----+---------+----------+
| 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中,它不支持子查询)。
答案 0 :(得分: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
答案 1 :(得分: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个案例,则该方法非常简短,易于理解和编辑。如果由于某种原因,您在同一nid
上会有2个完全相同的版本,那么结果可能是错误的。