add_order_discount_and_paid_amount.sql 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. -- =====================================================
  2. -- 订单表添加优惠金额和实付总金额字段
  3. -- 创建时间: 2026-04-13
  4. -- 说明:
  5. -- - discount_amount: 订单优惠金额(营销活动优惠 + 优惠券优惠)
  6. -- - paid_amount: 实付总金额 = total_amount - discount_amount
  7. -- =====================================================
  8. -- 添加优惠金额字段
  9. ALTER TABLE `t_order`
  10. ADD COLUMN `discount_amount` DECIMAL(10, 2) DEFAULT 0.00 COMMENT '订单优惠金额(营销活动优惠 + 优惠券优惠)' AFTER `total_amount`;
  11. -- 添加实付总金额字段
  12. ALTER TABLE `t_order`
  13. ADD COLUMN `paid_amount` DECIMAL(10, 2) DEFAULT 0.00 COMMENT '实付总金额 = total_amount - discount_amount' AFTER `discount_amount`;
  14. -- 更新已有数据:如果没有优惠金额,则paid_amount = total_amount
  15. UPDATE `t_order`
  16. SET `discount_amount` = 0.00,
  17. `paid_amount` = `total_amount`
  18. WHERE `discount_amount` IS NULL OR `paid_amount` IS NULL;
  19. -- 添加索引(可选,用于按优惠金额查询)
  20. -- ALTER TABLE `t_order` ADD INDEX `idx_discount_amount` (`discount_amount`);
  21. -- 验证
  22. SELECT
  23. id,
  24. order_no,
  25. total_amount,
  26. discount_amount,
  27. paid_amount,
  28. (total_amount - discount_amount) as calculated_paid_amount
  29. FROM `t_order`
  30. ORDER BY id DESC
  31. LIMIT 10;