我正在尝试执行一种通用类型的查询,但我不确定如何用语言表达它,以便我可以找到最佳实践的讨论和执行它的示例。
这是一个示例用例。
我有一个customers
表,其中包含有关客户的信息和一个orders
表。我想根据客户特征从 orders
中获取记录子集,并受到 customers
表中作为数据包含的“最早”和“最新”日期的限制。对于解决方案来说,将查询结果限制在这个日期范围内至关重要,该日期范围因客户而异。
客户
+------------+------------+----------+---------------------+-------------------+
| CustomerID | Location | Industry | EarliestActiveOrder | LatestActiveOrder |
+------------+------------+----------+---------------------+-------------------+
| 001 | New York | Finance | 2017-11-03 | 2019-07-30 |
| 002 | California | Tech | 2018-06-18 | 2019-09-22 |
| 003 | New York | Finance | 2015-09-30 | 2019-02-26 |
| 004 | California | Finance | 2019-02-02 | 2019-08-15 |
| 005 | New York | Finance | 2017-10-19 | 2018-12-20 |
+------------+------------+----------+---------------------+-------------------+
订单
+----------+------------+------------+---------+
| OrderID | CustomerID | StartDate | Details |
+----------+------------+------------+---------+
| 5430 | 003 | 2015-06-30 | ... |
| 5431 | 003 | 2016-03-31 | ... |
| 5432 | 003 | 2018-09-30 | ... |
| 5434 | 001 | 2018-11-05 | ... |
| 5435 | 001 | 2019-10-11 | ... |
用文字表达的示例用例是:“给我来自纽约金融客户的所有有效订单”。
期望的结果是从 orders
表中返回 OrderID
的 5431,5432,5434
的完整记录。
给定一个包含约 10^6 条记录的 orders
表,构建此类查询的一般好方法是什么?
最佳答案
您正在寻找加入:
select o.*
from orders o
inner join customers c
on c.Customer_id = o.Customer_id
and o.StartDate between c.EarliestActiveOrder and c.LatestActiveOrder
and c.Industry = 'Finance'
and c.Location = 'New York'
为了提高此查询的性能,请考虑以下索引:
orders(customer_id, StartDate)
customers(Customer_id, Industry, Location, EarliestActiveOrder, LatestActiveOrder)
关于SQL Server : table join based on record-dependent values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416340/