【发布时间】:2015-05-29 11:58:36
【问题描述】:
我使用下面的查询来选择电影年龄最小的演员。
SELECT production_cast.production_id, MIN(birthdate) FROM person
LEFT JOIN production_cast ON production_cast.person_id = person.id
WHERE birthdate IS NOT NULL
GROUP BY production_cast.production_id;
但是 IMDB 数据集非常庞大,需要 300 多秒才能完成。如果没有 GROUP BY 和 MIN,此查询将在 0.2 秒内运行:
SELECT production_cast.production_id FROM person
LEFT JOIN production_cast ON production_cast.person_id = person.id
WHERE birthdate IS NOT NULL;
数据库引擎是 MyIsam。 Mysql版本是5.7.2。我尝试在以下位置使用这些 BTREE 索引:
- production_cast.production_id
- person.birthdate
- person.birthdate 和 person.id
- production_cast.id 和 production_cast.production_id
explain 的简要输出是: 人物:范围, 索引: idx_Person_id_birthdate、idx_Person_id_birthdate、 额外:使用where;使用索引;使用临时的;使用文件排序
Production_cast: 参考, 索引: idx_Production_cast_person_id_production_id 额外:使用索引
person.id 和 production_cast.id 是主键索引。 production_cast.production_id 不是主键,但有索引。我可以做些什么来提高这个搜索查询的速度。
【问题讨论】:
-
explain select...对上述查询说了什么?将其添加到问题中。 -
请显示表格的布局。例如
product_cast.id是主键吗? -
@AbhikChakraborty 解释的结果是:对于人: 键: 生日,行: 366741, Extra: '使用索引条件;使用 MRR;使用临时的;使用文件排序' 对于生产演员: possiblekeys: PRIMARY, person_id key: person_id 所有 ids 都是主键,生日有索引 b>
-
你说数据库很大 => 有很多结果 => 一个根本无法滚动所有这些结果 => 为什么不使用分页器并限制结果呢? PS:尝试使用 subselect 摆脱 using filesort
-
我不明白,当一个完美的 PostgreSQL 存在时,为什么有人会故意选择 MySQL