我的查询需要基于第一次查询结果的其他信息。这是代码
$params = DB::select('SELECT vpl_ppid, vpl_name, vpl_display, vpl_filter
FROM vw_parameter_list
WHERE vpl_slug = :type', ['type' => $type]);
foreach ($params as $param) {
$pd_vals = DB::select('SELECT * FROM parameter_distinct_value WHERE pd_ppid = :vpl_ppid ORDER BY pd_value', ['vpl_ppid' => $param->vpl_ppid]);
$param->value_list = $pd_vals;
}
如上所示,我只需创建一个新数组($param->value_list
)即可将更多数据加载到其中。
如何通过消除foreach
内的查询来简化查询,以实现如上所述的速度和相同的输出。感谢
答案 0 :(得分:0)
您可以使用子查询:
$results = DB::select('
SELECT *
FROM
parameter_distinct_value
WHERE pd_ppid IN(
SELECT vpl_ppid FROM vw_parameter_list WHERE vpl_slug = :type
)
ORDER BY pd_value
', ['type' => $type]);
或加入
$results = DB::select('
SELECT pdv.*
FROM
parameter_distinct_value pdv
INNER JOIN vw_parameter_list vpl ON vpl.vpl_ppid = pdv.pd_ppid
WHERE vpl.vpl_slug = :type
ORDER BY pdv.pd_value
', ['type' => $type]);