php - Laravel quick integer lookup?
问题描述
We have a table with millions of rows. Recently we introduced an integer to act as a secondary key, which is just a unique integer column new_identifier = 1100327
and not yet defined as a secondary primary key.
This lookup query takes about 6 seconds in tinker. $this->id_lookup
is also an integer. and up to 50 seconds on horizon!
DB::table('my_big_table')->where('new_identifier', $this->id_lookup)->get();
How can we achieve the same performance as DB::table('my_big_table')->find($this->id_lookup);
which is almost instant?
Can we introduce a second primary key with something like $table->key(['id', 'new_identifier']);
?
How would this effect other lookups like MyBigTable::find($id);
that is performed elsewhere?
Update - changing column from int to index reduced lookup time from 50s to <0.01s
解决方案
您可以创建索引,在迁移中执行以下操作。
Schema::table('my_big_table', function (Blueprint $table) {
$table->index('new_identifier');
});
索引可以帮助您,但主键索引很特殊,它们是聚集的。这意味着它包含以下键的所有数据。虽然二级索引是非聚集的,但只会包含索引列和主键列。它仍然会提高性能,但在这个领域你需要大量研究不同索引对查询的影响,而且完全不是非黑即白。
推荐阅读
- c# - 应用运行时外关键字显示空白
- python - 如何使用左侧的日期时间索引和右侧的日期时间列将一个数据框(右)合并到另一个空数据框(左)?
- jenkins - 在不使用 Jenkins 中的任何插件的情况下屏蔽密码
- python-3.x - OpenCV 给出以下错误作为输出
- javascript - 如何在 js 中使用 sass 颜色函数
- computer-vision - 关于机器视觉技术的高动态范围与标准动态范围的优缺点的比较研究?
- c# - 受限 AppDomain 中的 C# 类继承自位于主 AppDomain 中的其他类
- javascript - Firestore forEach 迭代器中的异步/等待
- r - 将 lapply 与关键字参数一起使用
- android - 在调试时按下 Dart DevTools 中的调试按钮之前,无法按下 Flutter 应用程序中的按钮