简体   繁体   English

如何在 Knex.js 和 MySQL 中使用索引

[英]How to use index with Knex.js and MySQL

I created an index for a column with Knex.js, but I can't find any way to use it.我使用 Knex.js 为一列创建了索引,但找不到任何使用它的方法。

knex('my_table')
.select('*')
.where('my_table.status', '2')

The index name is: my_table_stats_idx索引名称为: my_table_stats_idx

I could do it with kex.raw() like:我可以用 kex.raw() 做到这一点,例如:

FROM my_table USE INDEX(my_table_stats_idx)

But I had to use the a complex query building that didn't fit with raw()但是我不得不使用不适合raw()的复杂查询构建

Is there a way to do that with Knex?有没有办法用 Knex 做到这一点?

In SQL, you don't tell the database which index it should use.在 SQL 中,您不会告诉数据库它应该使用哪个索引。 All you do is describe the result you want: the database makes the decision on how to process your statement.您所做的就是描述您想要的结果:数据库决定如何处理您的语句。 For this, the query planner takes in account various information, including, of course, available indexes.为此,查询计划器会考虑各种信息,当然包括可用索引。 If it estimates that a plan that uses the index is optimal, the index is used - else it is not.如果它估计使用该索引的计划是最佳的,则使用该索引 - 否则不是。

You don't tell what the definition of your index is.您不知道索引的定义是什么。 For your query, the optimal index probably is a single-column index on my_table(status) .对于您的查询,最佳索引可能是my_table(status)上的单列索引。

Finally: in most databases, there are ways to suggest the database to use a given index, through hints.最后:在大多数数据库中,有一些方法可以通过提示建议数据库使用给定的索引。 These are useful in edge cases where the query planner is not able to figure out things by itself.这些在查询计划器无法自己解决问题的边缘情况下很有用。 Your query clearly is not complex enough to qualify as such case.您的查询显然不够复杂,不足以构成这种情况。

You need knex.raw in the from clause您需要在 from 子句中使用 knex.raw

   knex
  .select('*')
   .where('my_table.status', '2')
  .from(knex.raw('my_table  FORCE INDEX(my_table_stats_idx)'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM