【问题标题】:MySQL and PHP advanced product sales: check multiple fieldsMySQL和PHP高级产品销售:检查多个字段
【发布时间】:2015-02-09 14:00:02
【问题描述】:

对不起标题,我不知道如何正确解释,我会在这里尝试。

我有 4 张桌子:

  • products(id, season_id(FK), year(4), brand_id(FK), price, ...)
  • seasons(id, name)
  • brands(id, name)
  • sales(id, season_id(FK), year(4), brand_id(FK), value(INT))

正如您已经猜到的那样,season_idbrand_id_id 的 FK。

现在,根据sales 表,产品的价格将被计算出来。我的问题是sales表可以有任意组合来计算价格。

为了更清楚,我会快速举个例子。

products 行:

  • id: 1, season_id: 3, year: 2013, brand_id 3, price: 100.00
  • id: 2, season_id: 3, year: 2015, brand_id 4, price: 100.00
  • id: 3, season_id: 4, year: 2014, brand_id 5, price: 100.00
  • id: 4, season_id: 5, year: 2014, brand_id 5, price: 100.00

sale 行:

  • season_id: 3, year: 2013, brand_id: 3, value: 5%
  • season_id: 3, year: 2014, brand_id: null, value: 10%
  • season_id: 4, year: 2015, brand_id: null, value: 15%
  • season_id: null, year: null, brand_id: 5, value: 20%

(所有字段都是可选的,但如果有季节就必须有年份)

举个例子

  • 第一个产品的价格将是 100 - 5%(第 3 季 + 2013 + 品牌 3)

  • 第二个产品的价格是100(匹配季节而不是年份)

  • 第三个产品的价格是100(匹配季节而不是年份)

  • 第四种产品的价格为 100 - 20%(任何季节 + 任何年份 + 品牌 5)

总而言之,我需要一种方法来了解每种产品适用什么销售。优先级是:

SeasonYearBrand > SeasonYear > Season > Year > Brand

现在我有一个查询,它获取所有产品和另一个用于所有销售的查询。在 foreach 中循环遍历所有产品,然后在另一个 foreach 循环遍历所有销售,最后检查要申请的销售。

我知道这很令人困惑,但我想知道是否有更好的方法。每页有 25 个产品,我在 sales 表中有 20 行,因此您可以看到事情变得很容易变得繁重。

【问题讨论】:

  • 为什么不通过 ajax 按需激活它,否则你的查询时间会飞到屋顶吗?
  • 产品3为什么没有减少20%? 20% 的销售记录是针对品牌 5 和任何季节和年份的,不是吗?
  • @ThorstenKettner 是的,那是我的错误。真实代码在sales表中还有2个字段,为简单起见我这里只写了3个。我的问题是在 PHP 中计算要应用的销售价值。

标签: php mysql database loops


【解决方案1】:

您可以使用 SQL 执行此操作。使用子查询获取最匹配的销售记录。候选日期是三个字段匹配或为空的所有销售记录。您按匹配质量排序。我将年度匹配排名最高,然后使用一些数学进行赛季然后品牌,我使用 MySQL 的功能将布尔表达式评估为 1 f0r TRUE 和 0 为 FALSE。因此,没有品牌的年份总比没有年份的品牌匹配要好。然后取第一条记录,即最佳匹配。我希望将 5% 的值存储为 0.5?否则,您将不得不更改公式。最后,如果没有任何记录匹配,我将价格乘以 1,从而保持价格。

select 
  id,
  season_id,
  year,
  price * 
  coalesce
  (
    (
      select 1 - s.value
      from sales s
      where coalesce(s.season_id, p.season_id) = p.season_id
      and coalesce(s.year, p.year) = p.year
      and coalesce(s.brand_id, p.brand_id) = p.brand_id
      order by
        (s.year is not null) * 4 + 
        (s.season_id is not null) * 2 + 
        (s.brand_id is not null) * 1 desc
      limit 1
    ), 1
  ) as calc_price
from products p;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多