diff --git a/web/backend/services/automation/jobs/account_capability_refresh.py b/web/backend/services/automation/jobs/account_capability_refresh.py index 78a6d13..fab5534 100644 --- a/web/backend/services/automation/jobs/account_capability_refresh.py +++ b/web/backend/services/automation/jobs/account_capability_refresh.py @@ -37,9 +37,20 @@ def _base_query(db: Session, now: datetime): ) .distinct() ) - stale_demand_state = exists( - select(AccountCommodityState.id).where( + active_lease = exists( + select(AccountLease.id).where( + AccountLease.active_account_id == Account.id, + ) + ) + # JOIN 比相关 EXISTS 更容易使用商品能力索引。当前生产账号池约 3 万, + # 原写法会按账号逐个探测商品状态,慢查询实测扫描 40 万行。 + return ( + db.query(Account) + .join( + AccountCommodityState, AccountCommodityState.account_id == Account.id, + ) + .filter( AccountCommodityState.platform == "douyu", AccountCommodityState.scope == "elite", AccountCommodityState.commodity_id.in_(pending_commodities), @@ -49,20 +60,13 @@ def _base_query(db: Session, now: datetime): AccountCommodityState.next_check_at.is_(None), AccountCommodityState.next_check_at <= now, ), + cookie_operable_filter(), + Account.auto_managed.is_(True), + Account.status.notin_(MANUAL_STATES), + Account.ck_check_status == "valid", + ~active_lease, ) - ) - active_lease = exists( - select(AccountLease.id).where( - AccountLease.active_account_id == Account.id, - ) - ) - return db.query(Account).filter( - cookie_operable_filter(), - Account.auto_managed.is_(True), - Account.status.notin_(MANUAL_STATES), - Account.ck_check_status == "valid", - stale_demand_state, - ~active_lease, + .distinct() )