-- 添加交易统计字段 -- 用于记录策略类型和持仓持续时间 -- 兼容MySQL 5.7+,使用动态SQL检查列和索引是否存在 USE `auto_trade_sys`; -- 1. 添加 strategy_type 列(如果不存在) SET @column_exists = ( SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = 'auto_trade_sys' AND table_name = 'trades' AND column_name = 'strategy_type' ); SET @sql = IF(@column_exists = 0, 'ALTER TABLE `trades` ADD COLUMN `strategy_type` VARCHAR(50) COMMENT ''策略类型: trend_following, mean_reversion'' AFTER `exit_reason`', 'SELECT "strategy_type 列已存在,跳过添加" as message' ); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; -- 2. 添加 duration_minutes 列(如果不存在) SET @column_exists2 = ( SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = 'auto_trade_sys' AND table_name = 'trades' AND column_name = 'duration_minutes' ); SET @sql2 = IF(@column_exists2 = 0, 'ALTER TABLE `trades` ADD COLUMN `duration_minutes` INT COMMENT ''持仓持续时间(分钟)'' AFTER `strategy_type`', 'SELECT "duration_minutes 列已存在,跳过添加" as message' ); PREPARE stmt2 FROM @sql2; EXECUTE stmt2; DEALLOCATE PREPARE stmt2; -- 3. 添加 idx_strategy_type 索引(如果不存在) SET @index_exists = ( SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema = 'auto_trade_sys' AND table_name = 'trades' AND index_name = 'idx_strategy_type' ); SET @sql3 = IF(@index_exists = 0, 'ALTER TABLE `trades` ADD INDEX `idx_strategy_type` (`strategy_type`)', 'SELECT "idx_strategy_type 索引已存在,跳过添加" as message' ); PREPARE stmt3 FROM @sql3; EXECUTE stmt3; DEALLOCATE PREPARE stmt3; -- 4. 添加 idx_exit_reason 索引(如果不存在) SET @index_exists2 = ( SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema = 'auto_trade_sys' AND table_name = 'trades' AND index_name = 'idx_exit_reason' ); SET @sql4 = IF(@index_exists2 = 0, 'ALTER TABLE `trades` ADD INDEX `idx_exit_reason` (`exit_reason`)', 'SELECT "idx_exit_reason 索引已存在,跳过添加" as message' ); PREPARE stmt4 FROM @sql4; EXECUTE stmt4; DEALLOCATE PREPARE stmt4; -- 验证:检查表结构 -- SHOW CREATE TABLE `trades`; -- 或者 -- DESCRIBE `trades`;