knex js 查询生成器性能

knex js query builder performance

knex.js 允许我们使用 js 构建查询。 假设我们有以下使用异步函数的代码逻辑:

const result1 = await knex('table1').select('something').where({condition1});
const result2 = await knex('table2').select('something').where({condition2: result1});
const result3 = await knex('table3').select('something').where({condition3: result2});

或者我们可以使用 knex.js 中的子查询构建,例如:

const subquery1 = knex('table1').select('something').where({condition1});
const subquery2 = knex('table2').select('something').where({condition2: subquery1});
const result3 = await knex('table3').select('something').where({condition3: subquery2});

显然这两种方法都会导致我们得到相同的结果 (result3),但在第一种方法中,我们在数据库上执行了 3 次查询,如果数据库在远程,这可能需要一些时间。

第二种方法是否可以使用子查询对数据库执行更少的查询,并节省一些时间?

是的。您可以通过调用 .toSQL() 方法查看查询构建器生成的查询。并通过设置环境变量 export DEBUG=knex:*

查看所有执行的查询