diff --git a/internal/data/business/analytics.go b/internal/data/business/analytics.go index 070c521..1e09daa 100644 --- a/internal/data/business/analytics.go +++ b/internal/data/business/analytics.go @@ -27,14 +27,16 @@ func analyticsPromotes(db *gorm.DB, scope business.AnalyticsScope, f business.An return q } keyword := strings.ToLower(strings.TrimSpace(f.PromoteName)) - hits := analyticsBasePromotes(db, scope, f, "hit").Select("1").Where("INSTR(LOWER(hit.account),?)>0 OR INSTR(LOWER(hit.nickname),?)>0", keyword, keyword).Where("hit.source_db=" + alias + ".source_db") + hits := analyticsBasePromotes(db, scope, f, "hit").Where("INSTR(LOWER(hit.account),?)>0 OR INSTR(LOWER(hit.nickname),?)>0", keyword, keyword) if scope.IncludeSub { root := "CASE WHEN hit.promote_level=1 THEN hit.id WHEN hit.top_promote_id>0 THEN hit.top_promote_id ELSE hit.id END" - hits = hits.Where("(" + alias + ".id=(" + root + ") OR " + alias + ".top_promote_id=(" + root + "))") - } else { - hits = hits.Where("hit.id=" + alias + ".id") + roots := hits.Select("DISTINCT hit.source_db," + root) + // Uncorrelated sets let MySQL materialize matching roots once. + // A correlated OR/EXISTS can rescan all channels for every outer row, + // especially when a keyword matches nothing. + return q.Where("("+alias+".source_db,"+alias+".id) IN (?) OR ("+alias+".source_db,"+alias+".top_promote_id) IN (?)", roots, roots) } - return q.Where("EXISTS (?)", hits) + return q.Where("("+alias+".source_db,"+alias+".id) IN (?)", hits.Select("hit.source_db,hit.id")) } func prepareAnalytics(db *gorm.DB, scope business.AnalyticsScope, f business.AnalyticsFilter) (bool, bool, error) { if !scope.Viewer.All {