[英]EF Query Performance Issue with MySQL
I am using Entity Framework 6 with MySQL 5.7.我正在使用带有 MySQL 5.7 的实体框架 6。 I am trying to tune queries and evaluate performance problems.
我正在尝试调整查询并评估性能问题。 There is a particular query showing up in the Slow Query Log.
慢查询日志中显示了一个特定的查询。 Here is an entry:
这是一个条目:
# Time: 2021-02-10T17:28:40.313796Z
# User@Host: user @ localhost [::1] Id: 89
# Query_time: 40.252085 Lock_time: 0.000044 Rows_sent: 1 Rows_examined: 758678
SET timestamp=1612978120;
SELECT
`Project1`.`Id`,
`Project1`.`Time`,
`Project1`.`Message`,
`Project1`.`Device_Id`,
`Project1`.`Type_Id`
FROM `DeviceEvents` AS `Project1`
WHERE (`Project1`.`Device_Id` = 2) AND (`Project1`.`Type_Id` = 7)
ORDER BY
`Project1`.`Time` DESC LIMIT 1;
As you can see the query is taking over 40 seconds.如您所见,查询耗时超过 40 秒。 If I copy this exact query in Workbench and run it, it takes 0.003 seconds.
如果我在 Workbench 中复制这个确切的查询并运行它,它需要 0.003 秒。 So, I am not sure what EF is doing that is affecting the execution time when it gets to MySQL.
所以,我不确定 EF 在做什么会影响它到达 MySQL 时的执行时间。 It looks like MySQL is examining a lot of rows even though there is an index on Device_Id, Type_Id, and Time.
看起来 MySQL 正在检查很多行,即使在 Device_Id、Type_Id 和 Time 上有索引。
After posting this I figured out the problem.发布后,我发现了问题所在。 Even though there were individual indexes on each of the appropriate columns, there was not a composite index.
即使每个适当的列上有单独的索引,也没有复合索引。 I added a composite index for (Device_Id, Type_Id, Time) and now the query returns almost immediately.
我为 (Device_Id, Type_Id, Time) 添加了一个复合索引,现在查询几乎立即返回。
I am not sure why it would run fast in Workbench without the composite index but not through Entity Framework.我不确定为什么它会在没有复合索引但不能通过实体框架的工作台中快速运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.