SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_wallet;

-- 用户钻石历史按 app/user/date 倒序分页；原 user_cycle 索引会因 cycle_key 位于时间前导致跨周期查询额外排序。
-- 在线新增窄复合索引，查询的 COUNT 和列表都可使用同一左前缀，并由 entry_id 稳定同毫秒顺序。
SET @has_host_period_diamond_user_time = (
  SELECT COUNT(*)
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'host_period_diamond_entries'
    AND INDEX_NAME = 'idx_host_period_diamond_entries_user_time'
);
SET @ddl = IF(
  @has_host_period_diamond_user_time = 0,
  'ALTER TABLE host_period_diamond_entries ADD INDEX idx_host_period_diamond_entries_user_time (app_code, user_id, created_at_ms, entry_id), ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
