0

我制作了一个小型修订系统,每次修改时都会存储文本的新版本。

该表如下所示:

+-------+-----+----------+
| revID | nID |   text   |
+-------+-----+----------+
|   1   |  1  |   foo    |
+-------+-----+----------+
|   2   |  1  |  newfoo  |
+-------+-----+----------+
|   3   |  2  |   bar    |
+-------+-----+----------+
|   4   |  2  |   baz    |
+-------+-----+----------+
|   5   |  3  |    a     |
+-------+-----+----------+

什么 SQL 语句会给我每个 nID 的最后插入的行?像这样:

+-------+-----+----------+
| revID | nID |   text1  |
+-------+-----+----------+
|   2   |  1  |  newfoo  |
+-------+-----+----------+
|   4   |  2  |   baz    |
+-------+-----+----------+
|   5   |  3  |    a     |
+-------+-----+----------+
4

1 回答 1

3

创建子查询的想法是获取每个的最大值 ,然后将其与表本身连接,但有两个连接条件:它匹配并且它也匹配RevIDNIDNIDRevID

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT nid, MAX(revID) maxID
            FROM tableName
            GROUP BY nid
        ) b ON a.nid = b.nid AND
                a.revID = b.maxID
于 2012-11-20T01:53:38.097 回答