简体   繁体   中英

Sql Join in Codeigniter?

I want to convert this query to codeigniter, but the last line - 'not in' is not working (I want the tests which are not there in assigned table)

SELECT * FROM (`tests` AS A) 
INNER JOIN `test_types` AS B ON `A`.`tst_test_type_id` = `B`.`tt_id` 
INNER JOIN `app_types` AS C ON `A`.`tst_app_type_id` = `C`.`at_id`
 AND tst_id not in (select ast_test_id from assigned_tests)

what so far I tried

  $this->db->select('*');
    $this->db->from('tests AS A');// I use aliasing make joins easier
    $this->db->join('test_types AS B', 'A.tst_test_type_id = B.tt_id', 'INNER');
    $this->db->join('app_types AS C', 'A.tst_app_type_id = C.at_id', 'INNER');
    $this->db->join('assigned_tests AS D', 'A.tst_id = D.ast_test_id', 'outer');

from the question you are saying "converting this query to codeigniter" but that's not true, you should have said "converting to active record", in fact codeigniter can use active record class or it can use native queries too, and they use less resources than active record I quote from the doc

Note: If you intend to write your own queries you can disable this class (Active Record) in your database config file, allowing the core database library and adapter to utilize fewer resources.

so to make it short, you can use your query like so :

$qry = $this->db->query('SELECT * FROM (`tests` AS A) 
INNER JOIN `test_types` AS B ON `A`.`tst_test_type_id` = `B`.`tt_id` 
INNER JOIN `app_types` AS C ON `A`.`tst_app_type_id` = `C`.`at_id`
AND tst_id not in (select ast_test_id from assigned_tests)');

return $qry->result();

You can submit the sub-query as a parameter by setting the escape flag to false .

$this->db->select('*');
$this->db->from('tests AS A');
$this->db->join('test_types AS B', 'A.tst_test_type_id = B.tt_id', 'INNER');
$this->db->join('app_types AS C', 'A.tst_app_type_id = C.at_id', 'INNER');
$this->db->join('assigned_tests AS D', 'A.tst_id = D.ast_test_id', 'outer');
$this->db->where('tst_id not in', '(select ast_test_id from assigned_tests)', false);

i found this working with IS NULL - pl post if some thing extra ordinary is there

$this->db->select('*');
        $this->db->from('tests AS A');
        $this->db->join('test_types AS B', 'A.tst_test_type_id = B.tt_id', 'INNER');
        $this->db->join('app_types AS C', 'A.tst_app_type_id = C.at_id', 'INNER');
        $this->db->join('assigned_tests AS D', 'A.tst_id = D.ast_test_id', 'left');
        $this->db->where('D.ast_test_id IS NULL');

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