【问题标题】:Search from specific to general from large ruleset从大型规则集中从特定到一般搜索
【发布时间】:2016-12-08 11:05:17
【问题描述】:

我有一个存储产品价格的表格,该表格从国家级别到商店级别进行分层组织。

create table price_list(
product_id number,
country_id number,
region_id number,
store_id number,
price number
)

我需要搜索此表以生成发票。函数的输入(这里不详述)就是这种模式(我会用json结构来解释):

{
    header : {country_id:5, region_id:234, store_id:345},
    items : {
       0:{product_id:1001, quantity:5}, 
       1:{product_id:299, quantity:1} 
       //, etc... 
      }
}

我想获取特定于该商店设置的产品的价格。

当然,如果每个字段都填写,我可以使用完整的选择语法搜索价格。

select price from price_list where product_id = ? and country_id = ? and region_id = ? and store_id = ?

但也有表格中的字段不完整的情况,例如仅填写 country_id 和 product_id,因为该产品在该国家/地区的所有地区和商店的价格都相同。假设由于非技术原因,我不想用完整的字段填充所有数据。下表中的示例数据如下所示。

product_id    country_id    region_id    store_id    price
1001          3             93           112         15
1001          3             93           113         15.5
1001          4             179                      14
1001          4             185                      13
1001          5                                      20
1001          5             999          999         25

如果我要执行这个请求,举个例子

{
    header : {country_id:5, region_id:300, store_id:500},
    items : {
       0:{product_id:1001, quantity:5}, 
    }
}

此查询不会返回结果,因为国家 5 没有为每个区域和商店指定具体价格,但区域 999 商店 999 除外。

select price from price_list where product_id = 1001 and country_id = 5 and region_id = 300 and store_id = 500

因为没有返回任何行,所以我需要泛化搜索,我从使用所有字段开始,如果没有找到价格,则逐个减少。

where product_id = 1001 and country_id = 5 and region_id = 300

但是,这仍然不会返回任何行。然后我再概括一下,这个搜索得到了值。

where product_id = 1001 and country_id = 5 

我目前的解决方案是详尽无遗的。有没有更好的方法来有效地做到这一点?环境是 php 5.4 和 CodeIgniter2 上的 Oracle 11g。

【问题讨论】:

    标签: php database algorithm filter


    【解决方案1】:

    为什么不创建一个包含 where 子句的变量:

    $priceWhereclause = "";
    $params = [];
    
    if(isset($productIdValue)){
       $priceWhereclause .= "product_id = ? ";
       $params[] = $productIdValue;
    }
    
    if(isset($countryIdValue)){
       $priceWhereclause .= "and country_id= ? ";
       $params[] = $countryIdValue;
    }
    

    您的查询将如下所示:

    select price from price_list where $priceWhereclause

    $params 放入execute($params) 函数中。

    【讨论】:

    • 很抱歉不清楚,我已经更新了我的问题。我认为问题不在查询中,因为所有值总是在请求中设置。问题是应该如何进行搜索。例如,如果我有国家 5 地区 999 的产品 1001 和商店 1000,我不能输入 where product_id = 1001 and country_id = 5 and region_id = 999 and store_id = 1000。它只适用于where product_id = 1001 and country_id = 5
    • 环绕(country_id = 5 AND store_id = 100) OR (country_id = 6 AND store_id = 110)
    • 我在其他地方使用SELECT price FROM price_list WHERE product_id = ? AND (country_id = ? OR country_id IS NULL) AND ... ORDER BY country_id ASC NULLS LAST, ...得到了建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2011-02-09
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多