简体   繁体   English

用文字快速查询,但用变量慢查询

[英]Query fast with literal but slow with variable

I am using Typeorm for SQL Server in my application.我在我的应用程序中为 SQL 服务器使用 Typeorm。 When I pass the native query like connection.query(select * from user where id = 1) , the performance is really good and it less that 0.5 seconds.当我通过像connection.query(select * from user where id = 1)这样的本机查询时,性能非常好,不到 0.5 秒。

If we use the findone or QueryBuilder method, it is taking around 5 seconds to get a response.如果我们使用findoneQueryBuilder方法,大约需要 5 秒才能得到响应。

On further debugging, we found that passing value directly to query like this,在进一步调试中,我们发现像这样直接将值传递给查询,

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

is faster than

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

Is there any optimization we can do to fix the issue with parameterized query?我们可以做任何优化来解决参数化查询的问题吗?

I don't know Typeorm but it seems to me clear the difference.我不知道 Typeorm,但在我看来区别很明显。 In one case you query the database for the whole table and filter it locally and in the other you send the filter to the database and it filters the data before it sends it back to the client.在一种情况下,您在数据库中查询整个表并在本地对其进行过滤,而在另一种情况下,您将过滤器发送到数据库并在将数据发送回客户端之前过滤数据。

Depending on the size of the table this has a big impact.根据表的大小,这会产生很大的影响。 Consider picking one record from 10 million.考虑从 1000 万条记录中挑选一条记录。 Just the time to transfer the data to the local machine is 10 million times slower.仅将数据传输到本地机器的时间就慢了 1000 万倍。

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

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