discount/scripts/migrate_discount_detail.sql

62 lines
2.3 KiB
SQL
Raw 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.

-- ============================================================
-- discount 模块迁移脚本:新增 discount_detail 表
-- 从旧版 discount 表迁移折扣值到 discount_detail
-- 日期: 2026-05-24
-- 执行前请备份数据库!
-- ============================================================
-- 1. 创建 discount_detail 表
CREATE TABLE IF NOT EXISTS discount_detail
(
`id` VARCHAR(32) NOT NULL COMMENT 'id',
`discountid` VARCHAR(32) NOT NULL COMMENT '折扣id',
`resellerid` VARCHAR(32) DEFAULT '*' COMMENT '商户id',
`prodtypeid` VARCHAR(32) DEFAULT NULL COMMENT '产品类型id',
`productid` VARCHAR(32) DEFAULT NULL COMMENT '产品id',
`discount` double(5,4) COMMENT '折扣值',
PRIMARY KEY(id),
INDEX idx_dd_discountid (discountid),
INDEX idx_dd_product (discountid, prodtypeid, productid)
)
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci
engine=innodb
COMMENT '折扣产品明细';
-- 2. 为 discount 表添加 name 字段(如果不存在)
ALTER TABLE discount ADD COLUMN IF NOT EXISTS `name` VARCHAR(100) COMMENT '折扣名称';
-- 3. 将现有 discount 记录的 discount 值迁移到 discount_detail
-- 为每条 discount 记录创建一条默认明细prodtypeid=NULL, productid=NULL
INSERT IGNORE INTO discount_detail (id, discountid, resellerid, prodtypeid, productid, discount)
SELECT
CONCAT('mig_', id, '_default') AS id,
d.id AS discountid,
d.resellerid,
NULL AS prodtypeid,
NULL AS productid,
d.discount
FROM discount d
WHERE d.discount IS NOT NULL AND d.discount > 0
AND NOT EXISTS (
SELECT 1 FROM discount_detail dd
WHERE dd.discountid = d.id
AND dd.prodtypeid IS NULL
AND dd.productid IS NULL
);
-- ============================================================
-- 验证步骤(执行后运行):
-- 1. 确认表创建成功:
-- SHOW TABLES LIKE 'discount_detail';
-- 2. 确认明细记录已迁移:
-- SELECT COUNT(*) FROM discount_detail;
-- SELECT * FROM discount_detail ORDER BY discountid;
-- 3. 确认 discount 表 name 字段存在:
-- DESCRIBE discount;
-- ============================================================
-- 回滚步骤(如需撤销):
-- DROP TABLE IF EXISTS discount_detail;
-- ALTER TABLE discount DROP COLUMN IF EXISTS name;
-- ============================================================