如何设计支持不同价格的产品变体价格存储架构?
产品变体价格存储方案设计
现有数据库表结构
product 表
| id | name |
|---|---|
| 1 | Puma T-shirt |
variant 表
| id | name |
|---|---|
| 1 | Size |
| 2 | Colour |
| 3 | Brand |
| 4 | Fabric |
options 表
| id | name |
|---|---|
| 1 | Small |
| 2 | Medium |
| 3 | Large |
| 4 | Puma |
| 5 | Adidas |
| 6 | Red |
| 7 | Green |
| 8 | cotton |
product_variant 表
| id | product_id | variant_id | 备注 |
|---|---|---|---|
| 1 | 1 | 1 | Puma T-shirt, Size |
| 2 | 1 | 2 | Puma T-shirt, Colour |
| 3 | 1 | 3 | Puma T-shirt, Brand |
| 4 | 1 | 4 | Puma T-shirt, Fabric |
product_variant_options 表
| id | product_variant_id | option_id | 备注 |
|---|---|---|---|
| 1 | 1 | 1 | (Puma T-shirt Size) , (Small) |
| 2 | 2 | 6 | (Puma T-shirt Colour), (Red) |
价格存储方案
针对不同产品变体组合的价格存储需求,以下是三种实用的架构方案,可根据业务场景选择:
方案一:新增variant_combination_price表(推荐)
适合需要为完整变体组合定价的场景(比如“Puma T-shirt + Small + Red + Puma + cotton”对应一个专属价格)。
表结构
CREATE TABLE variant_combination_price ( id INT PRIMARY KEY AUTO_INCREMENT, product_id INT NOT NULL, option_ids JSON NOT NULL, -- 存储选中的option_id集合,例:[1,6,4,8]对应Small、Red、Puma、cotton price DECIMAL(10,2) NOT NULL, currency VARCHAR(10) DEFAULT 'USD', -- 可选,支持多币种 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY unique_product_options (product_id, option_ids) -- 避免同一组合重复定价 );
示例数据
| id | product_id | option_ids | price | currency |
|---|---|---|---|---|
| 1 | 1 | [1,6,4,8] | 29.99 | USD |
| 2 | 1 | [2,7,4,8] | 32.99 | USD |
优势
- 逻辑直观,直接映射组合与价格,查询时匹配
option_ids即可获取对应价格 - 支持任意数量的变体组合,扩展性强
- 维护成本低,新增/修改价格仅需操作单表
方案二:扩展product_variant_options表(适合简单叠加定价)
如果价格是单个变体维度的线性叠加(比如Size加3元、Colour加2元),可直接在现有表中新增字段。
修改表结构
ALTER TABLE product_variant_options ADD COLUMN price_adjustment DECIMAL(10,2) DEFAULT 0;
示例数据
| id | product_variant_id | option_id | price_adjustment | 备注 |
|---|---|---|---|---|
| 1 | 1 | 1 | 0 | Small(无加价) |
| 2 | 1 | 2 | 3.00 | Medium(加价3元) |
| 3 | 2 | 6 | 2.00 | Red(加价2元) |
计算逻辑
在product表新增base_price字段存储产品基础价,最终价格 = 基础价 + 所有选中变体选项的price_adjustment总和。
优势
- 无需新增表,改动量小
- 适合定价规则简单的场景
局限性
- 无法处理复杂组合定价(比如“Small+Red”组合单独加价5元,而非各自加价的总和)
- 查询时需要聚合计算,性能略差
方案三:新增variant_price表(按单个变体维度定价)
如果价格仅按单个变体类型(比如不同Size对应不同价格)定价,而非组合,可使用此方案。
表结构
CREATE TABLE variant_price ( id INT PRIMARY KEY AUTO_INCREMENT, product_variant_id INT NOT NULL, option_id INT NOT NULL, price DECIMAL(10,2) NOT NULL, currency VARCHAR(10) DEFAULT 'USD', UNIQUE KEY unique_variant_option (product_variant_id, option_id), FOREIGN KEY (product_variant_id) REFERENCES product_variant(id), FOREIGN KEY (option_id) REFERENCES options(id) );
局限性
仅支持单维度定价,无法处理多变体组合的价格差异,适用场景较窄。
内容的提问来源于stack exchange,提问作者newbie_coder
相关产品推荐
相关产品推荐

