简体   繁体   中英

Codeigniter subquery with inner join

I am having a hard time converting my MySQL query to Codeigniter query builder. I cannot make the inner join with the same table. Like with my mySQL query. It is working on mySQL. Here is my query:

$sql = "SELECT answers.* FROM answers INNER JOIN
                (SELECT * FROM
                    (SELECT employee_id as test_employee_id, created_on as test_created_on FROM answers) as test
                GROUP BY test.test_employee_id)
                AS test on (test.test_employee_id = answers.employee_id AND test.test_created_on = answers.created_on)
                ORDER BY answers.created_on DESC";

Can you guys pls help me on this?? I am trying to convert it to Codeigniter query.

Try this one:

$this->db->select('answers.*');    
$this->db->from('answers');
$this->db->join('(SELECT * FROM
                    (SELECT employee_id as test_employee_id, created_on as test_created_on FROM answers) as test1
                GROUP BY test1.test_employee_id)
                AS test', 'test.test_employee_id = answers.employee_id AND test.test_created_on = answers.created_on');
$this->db->order_by("answers.created_on", "desc");
$query = $this->db->get(); 
return $query->result();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM