如何通过 php for 循环构建分面导航

how to build faceted navigation by php for loop

我想创建自动注入子查询。

示例如下:

我的代码将以此查询开头

SELECT product_id 
FROM  ecom_products_selected_features_values 
WHERE  feature_value_id  in (9)

我有数组

$numbers = array(6,5)

我想在 运行 时间低于查询

SELECT product_id 
FROM  ecom_products_selected_features_values 
WHERE  feature_value_id  in (9) AND product_id in (
    SELECT product_id 
    FROM  ecom_products_selected_features_values 
    WHERE  feature_value_id in (6) AND  product_id in (
        SELECT product_id 
        FROM  ecom_products_selected_features_values 
        WHERE  feature_value_id  in (5))
)

你真的不想做子查询。它们很慢 - 特别是对于大型数据集。你想参加。这就是我要做的:

$query = '
    select a.productid
    from ecom_products_selected_features_values a
';

这是查询的基础。现在,我循环遍历您的数组:

foreach($numbers as $i=>$n)
    $query.= "
        join ecom_products_selected_features_values b$i
        on a.productid=b$i.productid
        and b$i.feature_value_id in ($n)
    ";

为每个数字附加一个连接。每个连接都有一个基于数组键值的唯一 ID。但是,我们还没有限制到 9 个。添加:

$query.= 'where a.feature_value_id in (9)';

结果查询将是:

select a.product_id
from eps a
join eps b0
on a.productid=b0.productid
and b0.feature_value_id in (6)
join eps b1
on a.productid=b1.productid
and b1.feature_value_id in (5)
where a.feature_value_id in (9)

当然可以,为什么要用in?它很慢。我会将它们更改为 feature_value_id=$n.