php - 由于 for 循环内的 join 查询,页面加载时间较长

标签 php mysql codeigniter

我使用下面的代码创建了一个在页面中显示记录的功能,但由于加入查询,页面需要很长时间才能加载。任何人都可以找到问题并提供解决方案吗?

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;
    }

这个内部查询有单独的函数吗?

ginprocess

ginbale

最佳答案

嗯,执行查询 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/

相关文章:

javascript - 显式返回转义的 JSON 响应与仅在 Laravel/PHP 中返回数组

mysql - 如果不需要,是否应该使用表关系

mysql - 放入 CI 函数的长查询变得不起作用

php - 为什么某些 PHP 代码呈现为 HTML 注释

php - Laravel Eloquent Not Created_At 今天

mysql - 删除在另一个表中不存在 id 的所有行

php - Codeigniter - 我应该在 View 中访问 session 数据吗?

php - 使用 CodeIgniter 从 MySQL 数据库检索图像,而不使用上传库。是否可以?

php - Paypal IPN 数据

php - 试图用 WHERE NOT EXISTS 显示两个表中的数据