我如何加入“最新”记录?
我在 SQL Server 2000 数据库中有两个表,通过父子关系连接起来。在子数据库中,唯一键由父 ID 和日期戳组成。
我需要对这些表进行联接,以便仅联接每个子项的最新条目。
谁能给我任何提示我该如何解决这个问题?
I've got two tables in a SQL Server 2000 database joined by a parent child relationship. In the child database, the unique key is made up of the parent id and the datestamp.
I'm needing to do a join on these tables such that only the most recent entry for each child is joined.
Can anyone give me any hints how I can go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是我发现的最优化的方法。我针对多种结构对其进行了测试,与其他方法相比,这种方法的 IO 最低。
该示例将获取文章的最后修订版
Here's the most optimized way I've found to do this. I tested it against several structures and this way had the lowest IO compared to other approaches.
This sample would get the last revision to an article
如果您有一个表,其中仅包含每个父级的最新条目以及父级的 id,那么这会很容易,对吗?
您可以通过将子表连接到其本身来创建这样的表,只获取每个父 ID 的最大日期戳。像这样的东西(您的 SQL 方言可能会有所不同):
这会获取子表中对于该父 id 不存在更高时间戳的所有行。您可以在子查询中使用该表来连接到:
或直接将父表连接到其中:
If you had a table which just contained the most recent entry for each parent, and the parent's id, then it would be easy, right?
You can make a table like that by joining the child table on itself, taking only the maximum datestamp for each parent id. Something like this (your SQL dialect may vary):
That gets you all of the rows in the child table for which no higher timestamp exists, for that parent id. You can use that table in a subquery to join to:
or join the parent table directly into it:
使用此查询作为基础
请注意,CTE 定义不是查询的一部分 - 所以解决方案很简单
Use this query as a basis
Note that the CTE definition is not part of query-So the solution is simple