简单的SQL问题(MySQL)

时间:2009-02-03 10:17:26

标签: sql mysql

我有这个问题:

SELECT page.id, revision.title, revision.number
FROM page
    INNER JOIN revision ON page.id = revision.pageId

将返回类似的内容:

"1"   "Page Version A"   "1"
"1"   "Page Version B"   "2"
"1"   "Page Version C"   "3"

现在我只想为每个页面返回一行,其中包含最新(编号最高)修订版的数据。如果我这样做:

SELECT page.id, revision.title, revision.number
FROM page
    INNER JOIN revision ON page.id = revision.pageId
GROUP BY page.id

我明白了:

"1"   "Page Version A"   "1"

但我想:

"1"   "Page Version C"   "3"

有什么想法吗? 感谢。

4 个答案:

答案 0 :(得分:5)

添加类似于

的WHERE子句

WHERE revision.number =(从版本r中选择max(number),其中r.pageId = page.id)

答案 1 :(得分:2)

如果您只想选择一条记录,可以使用MySQL'LIMIT'关键字(类似于MSSQL'TOP')

例如:

SELECT page.id, revision.title, revision.number
FROM page
    INNER JOIN revision ON page.id = revision.pageId

ORDER BY revision.number DESC
LIMIT 0, 1

这将订购您的所有结果,然后选择最佳结果。

答案 2 :(得分:0)

如果这是一个你会运行多次的查询,我会考虑制作一个视图,选择每个pageid的最新版本:

create view LatestRevision
as 
Select pageid, max(number) from revision

然后查询

SELECT page.id, revision.title, revision.number
FROM page
    INNER JOIN revision ON page.id = revision.pageId
    INNER JOIN LatestRevision on revision.pageid = LatestRevision.pageid and revision.Number = LatestRevision.number

答案 3 :(得分:-1)

SELECT page.id, MAX(revision.number)
FROM page
INNER JOIN revision ON page.id = revision.pageId
GROUP BY page.id