我有以下表格(删除了不相关的内容):
create table Payment (
id int not null auto_increment,
status int not null,
primary key(id)
);
create table Booking (
id int not null auto_increment,
paymentId int not null,
nrOfPassengers int not null,
primary key(id),
key paymentFK (paymentId),
constraint paymentFK foreign key (paymentId) references Payment(id)
);
Booking
包含 ~456k 行和Payment
~331k 行。以下查询耗时 0.06 秒并返回 97 行:
select * from Booking b
join Payment p on b.paymentId = p.id
where p.status = 3
如果我添加一个order by
子句,则查询需要 4.4 秒,几乎慢了 100 倍:
select * from Booking b
join Payment p on b.paymentId = p.id
where p.status = 3
order by b.nrOfPassengers
解释第一个查询:
id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
1, SIMPLE, p, ALL, PRIMARY, NULL, NULL, NULL, 331299, Using where
1, SIMPLE, b, ref, paymentFK, paymentFK, 9, p.id, 1, Using where
第二个:
id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
1, SIMPLE, p, ALL, PRIMARY, NULL, NULL, NULL, 331299, Using where; Using temporary; Using filesort
1, SIMPLE, b, ref, paymentFK, paymentFK, 9, p.id, 1, Using where
我使用 MySQL 5.1.34。
查询中使用的where
子句从Payment
. where
我的印象是 MySQL 在使用(高度选择性)子句过滤结果集之前对结果集进行排序。我是对的吗?如果是这样,它为什么要这样做?我已经尝试分析这两个表,但查询计划没有变化。