如何设计表SQL表来存储范围及其对应的折扣值

时间:2018-10-15 14:17:37

标签: mysql

我想在MYSQL中创建表格以存储购买范围及其基于购买金额的折扣值。

例如

10% for purchase of 0-1000

20% for 1001-2000

30% for 2001-3000

&

40% for 3000+ (anything more than 3000)

我已按如下方式保存了前三个范围,但是最后一个范围的最大值应该是多少?

min      max     discount
-------------------------------
   0     1000    10%
1001     2000    20%
2001     3000    30%
3000+       ?    40%

或者还有其他方法吗?

2 个答案:

答案 0 :(得分:1)

您可以只存储最低金额

discounts table
-----------+----------
min_amount | discount
-----------+----------
1          | 10
1001       | 20
2001       | 30
3001       | 40

当然所有列都是integer值。

要获得2500的折扣,查询应为:

select discount
from discounts
where min_amount <= 2500
order by min_amount desc
limit 1

出于性能原因,应该为min_amount列建立索引。

答案 1 :(得分:1)

与@juergend一致,您的discounts表应仅具有“最小”金额和折扣。但是,我认为最好将两个值都存储为NUMERIC而不是INTEGER

+------------+----------+
| min_amount | discount |
+------------+----------+
|        0.0 |     0.10 |
|     1001.0 |     0.20 |
|     2001.0 |     0.30 |
|     3000.0 |     0.40 |
+------------+----------+

您还可以创建一个包含所需范围的派生表(例如,作为视图):

SELECT
    min_amount,
    (
        SELECT MIN(d2.min_amount) 
        FROM discounts d2 
        WHERE d2.min_amount > d1.min_amount
    ),
    discount
FROM discounts d1

将为您提供所需的范围:

+------------+------------+----------+
| min_amount | max_amount | discount |
+------------+------------+----------+
|        0.0 | 1001.0     |     0.10 |
|     1001.0 | 2001.0     |     0.20 |
|     2001.0 | 3000.0     |     0.30 |
|     3000.0 | NULL       |     0.40 |
+------------+------------+----------+

请注意,最高值的NULL具有max_amount

然后,如果您有一张购买表,则查询以获取折扣金额将如下所示:

SELECT
    p.purchase_amt AS original_amount,
    p.purchase_amt * (1.0 - dr.discount) AS discounted_amount,
    dr.discount
FROM purchases "p"
    LEFT JOIN discounts_range dr ON
        p.purchase_amt >= dr.min_amount
        AND (p.purchase_amt < dr.max_amount OR dr.max_amount IS NULL)

为您提供正确的结果:

+-----------------+-------------------+----------+
| original_amount | discounted_amount | discount |
+-----------------+-------------------+----------+
|         2500.00 |         1750.0000 |     0.30 |
|         2000.00 |         1600.0000 |     0.20 |
|         3005.00 |         1803.0000 |     0.40 |
+-----------------+-------------------+----------+