auto_trade_sys/backend/database/migrate_time_to_timestamp.sql
薇薇安 11e3532ac3 a
2026-01-17 20:23:49 +08:00

55 lines
2.0 KiB
SQL
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- 将时间字段从TIMESTAMP改为INT存储Unix时间戳秒数
-- 此脚本会将现有的datetime/timestamp数据转换为Unix时间戳
USE `auto_trade_sys`;
-- 步骤1添加新的INT类型字段临时字段
ALTER TABLE `trades`
ADD COLUMN `entry_time_ts` INT UNSIGNED NULL COMMENT '入场时间Unix时间戳秒数' AFTER `entry_time`,
ADD COLUMN `exit_time_ts` INT UNSIGNED NULL COMMENT '平仓时间Unix时间戳秒数' AFTER `exit_time`,
ADD COLUMN `created_at_ts` INT UNSIGNED NULL COMMENT '创建时间Unix时间戳秒数' AFTER `created_at`;
-- 步骤2将现有数据转换为Unix时间戳
-- 注意假设现有数据是北京时间UTC+8转换为UTC时间戳
UPDATE `trades`
SET `entry_time_ts` = UNIX_TIMESTAMP(`entry_time`)
WHERE `entry_time` IS NOT NULL;
UPDATE `trades`
SET `exit_time_ts` = UNIX_TIMESTAMP(`exit_time`)
WHERE `exit_time` IS NOT NULL;
UPDATE `trades`
SET `created_at_ts` = UNIX_TIMESTAMP(`created_at`)
WHERE `created_at` IS NOT NULL;
-- 步骤3删除旧的时间字段
ALTER TABLE `trades`
DROP COLUMN `entry_time`,
DROP COLUMN `exit_time`,
DROP COLUMN `created_at`;
-- 步骤4重命名新字段
ALTER TABLE `trades`
CHANGE COLUMN `entry_time_ts` `entry_time` INT UNSIGNED NOT NULL COMMENT '入场时间Unix时间戳秒数',
CHANGE COLUMN `exit_time_ts` `exit_time` INT UNSIGNED NULL COMMENT '平仓时间Unix时间戳秒数',
CHANGE COLUMN `created_at_ts` `created_at` INT UNSIGNED NOT NULL DEFAULT (UNIX_TIMESTAMP()) COMMENT '创建时间Unix时间戳秒数';
-- 步骤5更新索引
DROP INDEX IF EXISTS `idx_entry_time` ON `trades`;
CREATE INDEX `idx_entry_time` ON `trades` (`entry_time`);
-- 验证:查看转换后的数据
SELECT
id,
symbol,
entry_time,
FROM_UNIXTIME(entry_time) as entry_time_display,
exit_time,
FROM_UNIXTIME(exit_time) as exit_time_display,
created_at,
FROM_UNIXTIME(created_at) as created_at_display
FROM `trades`
ORDER BY id DESC
LIMIT 10;