-- crypto_binance_data表核心索引优化脚本
-- 针对500万+数据量的关键查询性能优化
-- 基于实际代码中的查询模式分析

-- 核心索引1: 主要查询模式索引
-- 覆盖: WHERE symbol = ? AND bar = ? ORDER BY timestamp
-- 这是代码中最常见的查询模式
CREATE INDEX idx_symbol_bar_timestamp ON crypto_binance_data (symbol, bar, timestamp);

-- 核心索引2: 时间范围查询索引  
-- 覆盖: WHERE symbol = ? AND bar = ? AND timestamp BETWEEN ? AND ?
-- 覆盖: WHERE symbol = ? AND bar = ? AND timestamp >= ? AND timestamp <= ?
# CREATE INDEX idx_symbol_bar_timestamp_range ON crypto_binance_data (symbol, bar, timestamp);

-- 核心索引3: 分组查询索引
-- 覆盖: GROUP BY symbol, bar
-- 覆盖: SELECT symbol, min(date_time), max(date_time) FROM crypto_binance_data WHERE bar='5m' GROUP BY symbol
CREATE INDEX idx_bar_symbol ON crypto_binance_data (bar, symbol);

-- 核心索引4: 技术指标查询索引
-- 覆盖: WHERE symbol = ? AND bar = ? AND macd_signal = ?
-- 覆盖: WHERE symbol = ? AND bar = ? AND kdj_signal = ?
-- 覆盖: WHERE symbol = ? AND bar = ? AND rsi_signal = ?
-- 覆盖: WHERE symbol = ? AND bar = ? AND boll_signal = ?
-- 覆盖: WHERE symbol = ? AND bar = ? AND ma_cross = ?
CREATE INDEX idx_symbol_bar_indicators ON crypto_binance_data (symbol, bar, macd_signal, kdj_signal, rsi_signal, boll_signal, ma_cross);

-- 核心索引5: 时间戳排序索引
-- 覆盖: ORDER BY timestamp DESC/ASC
-- 优化: 查询最新数据 ORDER BY timestamp DESC LIMIT 1
CREATE INDEX idx_timestamp_desc ON crypto_binance_data (timestamp DESC);

-- 核心索引6: 日期时间查询索引
-- 覆盖: WHERE date_time >= ? AND date_time <= ?
-- 覆盖: ORDER BY date_time
CREATE INDEX idx_date_time ON crypto_binance_data (date_time);

-- 核心索引7: 成交量查询索引
-- 覆盖: WHERE symbol = ? AND bar = ? AND volume > ?
-- 覆盖: ORDER BY volume DESC
CREATE INDEX idx_symbol_bar_volume ON crypto_binance_data (symbol, bar, volume);

-- 核心索引8: 价格查询索引
-- 覆盖: WHERE symbol = ? AND bar = ? AND close > ? AND close < ?
-- 覆盖: ORDER BY close DESC/ASC
CREATE INDEX idx_symbol_bar_close ON crypto_binance_data (symbol, bar, close);

-- 执行前检查现有索引
-- SHOW INDEX FROM crypto_binance_data;

-- 执行后验证索引效果
-- EXPLAIN SELECT * FROM crypto_binance_data WHERE symbol = 'BTC-USDT' AND bar = '5m' ORDER BY timestamp DESC LIMIT 100;
-- EXPLAIN SELECT symbol, min(date_time), max(date_time) FROM crypto_binance_data WHERE bar='5m' GROUP BY symbol;
-- EXPLAIN SELECT * FROM crypto_binance_data WHERE symbol = 'BTC-USDT' AND bar = '5m' AND timestamp BETWEEN 1640995200000 AND 1641081600000;
