linq 后台代码:主要含义: 就是先根据PersonID分组查询,去掉重复的PersonID。 然后在这个结果集里面。根据PersonID,AlarmStatus升序,AlarmRecordID降序,获取最新的AlarmRecordID。 然后两个合并为结果集。转为mysql 的SQL语句为 SELECT t.PersonID,(SELECT AlarmRecordID FROM AlarmRecord WHERE OrganizationID = 4 AND IsDeleted = 0 AND PersonID = t.PersonID ORDER BY AlarmStatus ASC,AlarmRecordID DESC LIMIT 1) AS AlarmRecordIDFROM AlarmRecord t WHERE t.OrganizationID = 4 AND t.IsDeleted = 0 GROUP BY t.PersonID我想优化标记为红色部分的SQL,请问怎么优化?
1 回答
繁华开满天机
TA贡献1816条经验 获得超4个赞
首先修改sql :
SELECT t.PersonID,(SELECT AlarmRecordID FROM AlarmRecord WHERE PersonID = t.PersonID ORDER BY AlarmStatus ASC,AlarmRecordID DESC LIMIT 1) AS AlarmRecordIDFROM AlarmRecord t WHERE t.OrganizationID = 4 AND t.IsDeleted = 0 GROUP BY t.PersonID
通过创建索引来优化
CREATE INDEX `idx_AlarmRecord_PersonID` ON `AlarmRecord`(`PersonID`, `AlarmStatus`);
通过创建索引,查询会快很多。如果不通过创建索引,有什么好的方法吗?
添加回答
举报
0/150
提交
取消