You need to enable JavaScript to run this app. 如何使用MySQL与PHP基于单表价格数据实现指定成本下的商品组合查询
优惠活动
大模型
产品
解决方案
定价
更多

如何使用MySQL与PHP基于单表价格数据实现指定成本下的商品组合查询

商品组合成本上限匹配实现方案

背景说明

现有sample_records数据表,结构如下:

  • sr_id:自增主键
  • skuid:商品唯一识别编号
  • price:对应商品的单价

表内示例数据:

sr_id | skuid | price
----------------------
   1  | SKOO1 | 12
   2  | SKOO2 | 7
   3  | SKOO3 | 56
   4  | SKOO4 | 3 
   5  | SKOO5 | 23
   6  | SKOO6 | 50 
   7  | SKOO7 | 34
   8  | SKOO8 | 5 
   9  | SKOO9 | 23
  10  | SKO10 | 56 
  11  | SKO11 | 101
  12  | SKO12 | 4 
  13  | SKO13 | 23
  14  | SKO14 | 56

需求为给定总成本上限(例:500),输出所有总成本不超过该上限的商品组合,包含skuid组合、对应商品数量、组合总成本三个字段。


可行实现方案

方案1:MySQL递归CTE实现(适合在数据库内直接计算)

该方案适合商品数量≤10、成本上限不高的场景,组合数过高时会存在性能问题:

-- 先定义总成本上限变量
SET @max_cost = 500;

WITH RECURSIVE goods AS (
    -- 给商品生成连续序号方便递归遍历
    SELECT ROW_NUMBER() OVER(ORDER BY sr_id) AS gid, skuid, price FROM sample_records
),
num_seq AS (
    -- 递归生成0到最大可买数量的数字序列,适配低成本商品的数量上限
    SELECT 0 AS cnt UNION ALL SELECT cnt+1 FROM num_seq WHERE cnt < FLOOR(@max_cost / (SELECT MIN(price) FROM goods))
),
combinations AS (
    -- 递归起始节点:第一个商品的所有可买数量组合
    SELECT 
        1 AS current_gid,
        CAST(g.skuid AS CHAR(2000)) AS skuid_list,
        CAST(n.cnt AS CHAR(2000)) AS quantity_list,
        g.price * n.cnt AS total_cost
    FROM goods g 
    JOIN num_seq n ON n.cnt * g.price <= @max_cost
    WHERE g.gid = 1 AND n.cnt > 0
    UNION ALL
    -- 递归叠加后续商品的不同数量
    SELECT 
        g.gid AS current_gid,
        CONCAT(c.skuid_list, ',', g.skuid) AS skuid_list,
        CONCAT(c.quantity_list, ',', n.cnt) AS quantity_list,
        c.total_cost + n.cnt * g.price AS total_cost
    FROM combinations c
    JOIN goods g ON g.gid = c.current_gid + 1
    JOIN num_seq n ON c.total_cost + n.cnt * g.price <= @max_cost AND n.cnt > 0
    UNION ALL
    -- 新增仅选当前商品的分支,避免漏项
    SELECT 
        g.gid AS current_gid,
        CAST(g.skuid AS CHAR(2000)) AS skuid_list,
        CAST(n.cnt AS CHAR(2000)) AS quantity_list,
        g.price * n.cnt AS total_cost
    FROM goods g
    JOIN num_seq n ON n.cnt * g.price <= @max_cost
    WHERE g.gid > 1 AND n.cnt > 0
)
-- 输出最终结果
SELECT 
    ROW_NUMBER() OVER(ORDER BY total_cost DESC) AS `ROW`,
    skuid_list AS `skuid`,
    quantity_list AS `quantity`,
    total_cost AS `cost`
FROM combinations
ORDER BY total_cost DESC;

方案2:Python实现(更灵活,适合组合数较高的场景)

可通过剪枝逻辑优化性能,也支持自定义输出过滤规则:

# 模拟从数据库查询到的商品列表
goods = [
    ("SKOO1",12),("SKOO2",7),("SKOO3",56),("SKOO4",3),("SKOO5",23),
    ("SKOO6",50),("SKOO7",34),("SKOO8",5),("SKOO9",23),("SKO10",56),
    ("SKO11",101),("SKO12",4),("SKO13",23),("SKO14",56)
]
max_cost = 500
result = []

# 递归生成所有合法组合
def gen_comb(index, cur_skus, cur_quans, cur_cost):
    if index == len(goods):
        if cur_cost > 0:
            result.append((
                ",".join(cur_skus),
                ",".join(map(str, cur_quans)),
                cur_cost
            ))
        return
    skuid, price = goods[index]
    max_cnt = (max_cost - cur_cost) // price
    # 遍历当前商品的所有可选数量
    for cnt in range(0, max_cnt + 1):
        if cnt == 0:
            gen_comb(index+1, cur_skus, cur_quans, cur_cost)
        else:
            gen_comb(
                index+1,
                cur_skus + [skuid],
                cur_quans + [cnt],
                cur_cost + cnt * price
            )

# 执行组合生成
gen_comb(0, [], [], 0)
# 按总成本倒序排列
result.sort(key=lambda x: -x[2])

# 格式化输出
print("ROW | skuid                  | quantity  | cost")
print("-"*50)
for row_id, item in enumerate(result, 1):
    print(f"{row_id:<3d} | {item[0]:<22} | {item[1]:<9} | {item[2]:<4d}")

如果不需要输出所有组合,只需要成本接近上限的组合,可以在输出前增加过滤条件,比如result = [i for i in result if i[2] >= 490]大幅减少输出量。

内容的提问来源于stack exchange,提问作者Manikandan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 10:30:05