查询效率 - 从表中选择 2 个最新的“group/batch"记录

问题描述:

我们测试了一个非常有趣的 SQL 查询.不幸的是,事实证明这个查询运行有点慢 - O(n2) - 我们正在寻找一个优化的解决方案,或者也可能是一个完全不同的解决方案?

We have a tested a quite interesting SQL query. Unfortunately, It turned out that this query runs a little bit slow - O(n2) - and we are looking for a optimized solution or maybe also a totally different one?

目标:

We would like to get for:
 - some customers ("record_customer_id"), e.g. ID 5
     - the latest 2 "record_init_proc_id" 
       - for every "record_inventory_id"

http://www.sqlfiddle.com/#!9/07e5d/4

查询工作正常并显示正确的结果,但至少使用了两次全表扫描,这在要扫描的行太多时当然很糟糕.

The query works fine and shows the correct results but uses at least two full table scans which is of course horrible when having too many rows to scan.

是否可以 (a) 首先选择特定日期范围内的所有 record_customer_id(s),保存该查询的结果,然后 (b) 在这些保存的结果上运行 SQL 中的工作查询?

Is it possible to (a) select first all record_customer_id(s) in a specific date range, saving the results of that query and then (b) run the working query in SQL fiddle over these saved results?

或者是否有一种完全不同的方法具有出色的性能?

Or is there maybe a totally different approach out there which has a great performance?

非常感谢任何帮助!

我在我的 Groupwise-Max 博客