diff --git a/sql/migrate_kpi_area_info_area_id_index.sql b/sql/migrate_kpi_area_info_area_id_index.sql new file mode 100644 index 0000000..da86588 --- /dev/null +++ b/sql/migrate_kpi_area_info_area_id_index.sql @@ -0,0 +1,18 @@ +-- 分区明细按 AreaId 全量/分页查询时避免 filesort 打满 sort_buffer(查价 LIVE 路径易踩) +SET @db := DATABASE(); + +SET @idx := ( + SELECT COUNT(1) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_kpi_area_info' + AND INDEX_NAME = 'idx_kpi_info_area_id' +); +SET @sql := IF( + @idx = 0, + 'ALTER TABLE `t_kpi_area_info` ADD KEY `idx_kpi_info_area_id` (`AreaId`, `Id`)', + 'SELECT ''idx_kpi_info_area_id already exists'' AS info' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; diff --git a/src/Oms.SqlSugarCore/Channels/KpiAreaRepository.cs b/src/Oms.SqlSugarCore/Channels/KpiAreaRepository.cs index b06e0e4..c887260 100644 --- a/src/Oms.SqlSugarCore/Channels/KpiAreaRepository.cs +++ b/src/Oms.SqlSugarCore/Channels/KpiAreaRepository.cs @@ -21,9 +21,10 @@ public class KpiAreaRepository : OmsSqlSugarRepository, IKpiAreaReposit public async Task> GetInfosAsync(int areaId, int pageIndex, int pageSize, CancellationToken cancellationToken = default) { var db = await GetDbContextAsync(cancellationToken); + // 依赖 idx_kpi_info_area_id (AreaId, Id),避免大分区 filesort return await db.Queryable() .Where(x => x.AreaId == areaId) - .OrderBy(x => x.Id, SqlSugar.OrderByType.Desc) + .OrderBy(x => x.Id, OrderByType.Desc) .ToPageListAsync(pageIndex, pageSize, cancellationToken); } @@ -66,9 +67,10 @@ public class KpiAreaRepository : OmsSqlSugarRepository, IKpiAreaReposit public async Task> GetAllInfosByAreaIdAsync(int areaId, CancellationToken cancellationToken = default) { var db = await GetDbContextAsync(cancellationToken); + // 大分区表(如美区邮编)全量 ORDER BY 会打满 MySQL sort_buffer 导致 500; + // 需要稳定顺序的调用方在内存中排序(如 EnsurePackAsync)。 return await db.Queryable() .Where(x => x.AreaId == areaId) - .OrderBy(x => x.Id) .ToListAsync(cancellationToken); }