我想创建自动注入子查询。
这是一个例子:
我的代码将以这个查询开始
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)
当然,为什么用在?它很慢。我会将其更改为feature_value_id=$n。