【问题标题】:Query fast with literal but slow with variable用文字快速查询,但用变量慢查询
【发布时间】:2021-08-05 16:59:57
【问题描述】:

我在我的应用程序中使用 Typeorm for SQL Server。当我通过像 connection.query(select * from user where id = 1) 这样的原生查询时,性能非常好,不到 0.5 秒。

如果我们使用 findoneQueryBuilder 方法,大约需要 5 秒才能得到响应。

在进一步调试中,我们发现像这样直接将值传递给查询,

return getConnection("vehicle").createQueryBuilder() 
                               .select("vehicle")
                               .from(Vehicle, "vehicle") 
                               .where("vehicle.id='" + id + "'").getOne();

return getConnection("vehicle").createQueryBuilder() 
                               .select("vehicle")
                               .from(Vehicle, "vehicle") 
                               .where("vehicle.id =:id", {id:id}).getOne();

我们可以做任何优化来解决参数化查询的问题吗?

【问题讨论】:

  • 还有什么问题?)
  • 我们可以做任何优化来解决参数化查询的问题吗?

标签: sql node.js typescript typeorm typeorm-datamapper


【解决方案1】:

我不知道 Typeorm,但在我看来区别很明显。在一种情况下,您在数据库中查询整个表并在本地对其进行过滤,而在另一种情况下,您将过滤器发送到数据库,并在将数据发送回客户端之前对其进行过滤。

根据表的大小,这会产生很大的影响。考虑从 1000 万条记录中挑选一条记录。仅将数据传输到本地机器的时间就慢了 1000 万倍。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多