gpt4 book ai didi

mysql - 日期范围内的记录 - 性能

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:11 26 4
gpt4 key购买 nike

这里有个问题。我有一张 table

flightdetails
-----------+-------------
flightName | varchar(200)
departure | date
arrival | date

我想获取给定日期范围内的所有航类。 fromDate 或 toDate 应在给定的日期范围内。我知道一个简单的查询会给我结果

select flightname from flightdetails where (departure between fromDate and toDate)
or (arrival between fromDate and toDate);

但这对性能不利,因为我使用 OR 条件。谁能提出一个也有利于性能的更好的解决方案

最佳答案

这是针对此问题的常见解决方案。每个子查询都可以通过这种方式使用索引。

select flightname from flightdetails where departure between fromDate and toDate
union
select flightname from flightdetails where arrival between fromDate and toDate;

来自@SalmanA 的评论

你是对的,上面的查询遗漏了这样的情况:

departure < fromDate < toDate < arrival

既然出发和到达都不在日期范围内,当然日期范围是包含在航类时间里的。

这是另一个基于您的解决方案,但它在出发和到达时都使用了索引。请务必为每个条件创建复合索引:

create index flt_d on flightdetails(flightname, departure);
create index flt_a on flightdetails(flightname, arrival);

select f1.flightname
from flightdetails f1
join flightdetails f2 use index (flt_a)
on f1.flightname = f2.flightname
where f1.departure <= toDate
and f2.arrival >= fromDate;

我对此进行了测试,我不得不使用“使用索引”提示来诱导它使用第二个索引,但是当我这样做时,我得到了这个优化器计划:

*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: f1
type: index
possible_keys: flt_d,flt_a
key: flt_d
key_len: 20
ref: NULL
rows: 3
Extra: Using where; Using index
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: f2
type: ref
possible_keys: flt_a
key: flt_a
key_len: 12
ref: test.f1.flightname
rows: 1
Extra: Using where; Using index

关于mysql - 日期范围内的记录 - 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com