我使用下面的代码创建了一个在页面中显示记录的功能,但由于加入查询,页面需要很长时间才能加载。任何人都可以找到问题并提供解决方案吗?
public function baleList($program_id) {
$this->db->select('id');
$this->db->from(GIN_PROCESS);
$this->db->where('ginner_id', $this->prscr_id);
$this->db->where('program', $program_id);
$this->db->order_by('id', 'DESC');
$result = $this->db->get()->result_array();
$id_array = array_column($result, 'id');
$bales_list = array();
foreach ($id_array as $id) {
$this->db->select('gp.id, gp.lot_no, SUM(gb.weight) AS weight, SUM(gb.staple) AS staple, SUM(gb.mic) AS mic, SUM(gb.strength) AS strength, SUM(gb.trash) AS trash, gb.color_grade');
$this->db->from(GIN_BALES . ' gb');
$this->db->join(GIN_PROCESS . ' gp', 'gp.id=gb.process_id');
$this->db->where('gb.process_id', $id);
$this->db->where('gb.sold_status', 0);
$lot_details = $this->db->get()->result();
if (count($lot_details) > 0) {
$this->db->select('*');
$this->db->from(GIN_BALES);
$this->db->where('sold_status', 0);
$this->db->where('process_id', $id);
$bales = $this->db->get()->result();
if (count($bales) > 0) {
$lot_details[0]->bales = $bales;
$bales_list[] = $lot_details[0];
}
}
}
return $bales_list;
}
这个内部查询有单独的函数吗?
最佳答案
嗯,执行查询 n 次肯定是性能 killer 。尝试添加“GROUP BY gb.process_id”,删除循环本身并使用“WHERE gb.process_id IN ($id_array)”。您可能需要在选择中使用“ANY_VALUE()”来选择没有最小值/最大值等的列。
关于php - 由于 for 循环内的 join 查询,页面加载时间较长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56739280/