mySql 计算所有最新版本

mySql count all latest versions

不幸的是,我昨天提出了一个问题,我没有很好地解释自己 - 其中之一就是一天结束的事情。

反正我有一个table叫文件...

+----+--------------------------------------+-----------+---------+---------+
| id | document_guid                        | title     | version | payload |
+----+--------------------------------------+-----------+---------+---------+
| 1  | 0D2753BE-583B-42CE-B0DA-1FD0171D95C0 | animation | 1       | {}      |
| 2  | 0D2753BE-583B-42CE-B0DA-1FD0171D95C0 | animation | 2       | {}      |
| 3  | 1C2A1131-0261-4D58-81AA-EFAB5285B282 | formation | 1       | {}      |
| 4  | 1E17403F-C590-4CE4-9E79-E1B7C98F97F1 | session   | 1       | {}      |
| 4  | 1E17403F-C590-4CE4-9E79-E1B7C98F97F1 | session   | 2       | {}      |
+----+--------------------------------------+-----------+---------+---------+

如您所见,我们可以拥有同一文档的多个版本(由 document_guid 引用)。我需要的是 table 中所有文档的计数,不包括过时版本。即如果文档 1E17403F-C590-4CE4-9E79-E1B7C98F97F1 有两个版本,如上例所示,那么它应该只占总数中的一个文档。

我真的希望这比我的最后一个问题更有意义。

我遇到的主要问题是我需要一个类似的查询 returns 所有最新版本,而不仅仅是计数。

计算不同 document_guids:

select count(distinct document_guid) from documents

要return每个文件的最新版本,你可以做一个GROUP BY(如user2864740的回答),或者NOT EXISTS:

select * from documents d1
where not exists (select 1 from documents d2
                  where d2.document_guid = d1.document_guid
                    and d2.version > d1.version)

即return 如果没有其他相同 document_guid 具有更高版本号的行。

有用的查询可能如下所示:

-- select the maximum version (and other information, per group)
-- can also add a 'count(1) as version_count' if required
select max(version) as latest_version, title, document_guid
from documents
-- from each group, as divided up by the same guid *see note 1
group by document_guid, title

本次查询returns最新版本号;每个文档总是 "one latest version"。


1 标题可能是规范化的中断,需要成为组的一部分才能包含在结果列中;如果不需要,可以将其删除。

如果标题是必填字段,可以跨版本更改,则需要以不同的方式编写 - 首先找到 "latest version",然后将其与适当的行。一个例子:

select t.latest_version, d.title, d.document_guid
from documents d
join (
  select max(version) as latest_version, document_guid
  from documents
  group by document_guid
) t
on t.document_guid = d.document_guid and t.latest_version = d.version

当然,这假设密钥为 (document_guid, version)