需要帮助查询数据库以显示最新版本

时间:2017-02-24 14:57:50

标签: mysql database

我使用名为Page的表来处理mysql数据库。有没有办法只从每个页面中提取最新版本?

ID      Page Title      Version
0001    Homepage        1
0002    Homepage        2
0003    Homepage        3
0004    Contact         1
0005    Contact         2
0006    Basket          1
0007    Basket          2
0008    Basket          3
0009    Basket          4

我需要什么:

ID      Page Title      Version
0003    Homepage        3
0005    Contact         2
0009    Basket          4

3 个答案:

答案 0 :(得分:1)

您可以使用MAXGROUP BY,如下所示:

 SELECT MAX(ID)
        ,PageTtile
        ,MAX(version)
    FROM Page
    GROUP BY PageTitle

答案 1 :(得分:0)

你也可以使用row_number(),如下所示

    SELECT * FROM (
SELECT Row_Number() over (partition by Title order by Version DESC) As rn, Page, Title, Version FROM Page) a
where rn = 1

答案 2 :(得分:0)

尝试此查询 -

SELECT t1.* FROM tbl t1
 JOIN (SELECT PageTitle, MAX(Version) Version FROM tbl GROUP BY PageTitle) t2
   ON t1.PageTitle = t2.PageTitle AND t1.Version = t2.Version;

输出:

3 Homepage  3
5 Contact   2
9 Basket    4