如何将 CodeIgniter 与 FROM ( .... ) AS 一起使用

问题描述 投票:0回答:1

我的查询是

$this->db->query("
    SELECT table_A.*
    FROM (
        SELECT MIN(table_A.table_A_id) AS table_A_id
        FROM (
            SELECT table_A.table_b_id
            FROM table_A
            JOIN table_b ON table_b.table_b_id = table_A.table_b_id
            WHERE table_b.table_c_id = 0 AND table_A.is_correct = 'y'
            GROUP BY table_A.table_b_id
        ) AS table_b_target
        JOIN table_A ON table_A.table_b_id = table_b_target.table_b_id
        GROUP BY table_A.table_b_id
    ) AS first_row
    JOIN table_A ON table_A.table_A_id = first_row.table_A_id
    WHERE table_A.is_correct = 'y'
")->result();

我尝试过这个,但不起作用。

$this->db->select("table_A.*");
$this->db->from("","AS first_row");

$this->db->group_start();
$this->db->select_min('table_A.table_A_id');
$this->db->from("","AS table_b_target");

$this->db->group_start();
$this->db->select("table_A.table_b_id");
$this->db->from("table_A");
$this->db->join("table_b", "table_b.table_b_id = table_A.table_b_id");
$this->db->where("table_b.table_c_id =", 0);
$this->db->where("table_A.is_correct =", "y");
$this->db->group_by("table_A.table_b_id");
$this->db->group_end();

$this->db->join("table_A", "table_A.table_b_id = table_b_target.table_b_id");
$this->db->group_by("table_A.table_b_id");
$this->db->group_end();

$this->db->join("table_A", "table_A.table_A_id = first_row.table_A_id");
$this->db->where("table_A.is_correct =", "y");
$result = $this->db->get()->result();

有人可以展示一个使用

$this->db->from
从另一个查询中搜索特定数据的 CodeIgniter 示例吗?

我尝试将它们分为 3 个步骤(搜索 -> 获取结果 -> 搜索每个结果 -> 获取结果......),但它比一个查询慢。

php codeigniter
1个回答
0
投票

尝试一次

$this->db->select('table_A.*');
$this->db->from('(SELECT MIN(table_A.table_A_id) AS table_A_id
                FROM (SELECT table_A.table_b_id
                      FROM table_A
                      JOIN table_b ON table_b.table_b_id = table_A.table_b_id
                      WHERE table_b.table_c_id = 0 AND table_A.is_correct = "y"
                      GROUP BY table_A.table_b_id) AS table_b_target
                JOIN table_A ON table_A.table_b_id = table_b_target.table_b_id
                GROUP BY table_A.table_b_id) AS first_row', NULL, FALSE);

$this->db->join('table_A', 'table_A.table_A_id = first_row.table_A_id');
$this->db->where('table_A.is_correct', 'y');

$result = $this->db->get()->result();
© www.soinside.com 2019 - 2024. All rights reserved.