Codeigniter JOIN (SELECT query

后端 未结 3 1818
慢半拍i
慢半拍i 2020-12-31 10:38

It is possible to generate the following query by CI Query Builder class ?

SELECT name 
       FROM table1 t1 
                   JOIN 
                              


        
相关标签:
3条回答
  • 2020-12-31 11:05

    this library can help you to use sub queries with query builder have look on the doc of this library

    sub query with query builder

    0 讨论(0)
  • 2020-12-31 11:16

    Well there are a couple of ways of doing it. One way is here which is a hack.

    How can I rewrite this SQL into CodeIgniter's Active Records?

    This other way is very simple.

    $this->db
            ->select('ID')
            ->from('table2')
            ->order_by('id')
            ->limit('5');   
    
    $subquery = $this->db->_compile_select();
    
    $this->db->_reset_select(); 
    
    $query  =       $this->db
                        ->select('t1.name')
                        ->from('table1 t1 ')
                        ->join("($subquery)  t2","t2.id = t1.t2_id")
                        ->get('table1 t1');
    

    Some point about it.
    You are bound to use from clause in subqueries because get runs the query.
    In codeigniter 2 _compile_select and _reset_select can not be accessed because they are protected methods.
    You may have to remove the keyword before both methods in system/database/DB_active_rec.php

    This article is useful too.

    0 讨论(0)
  • 2020-12-31 11:19

    in CI3, simply use the fourth parameters for escape

    $this->db->from('table')
    ->join('SELECT id from table2 where something=%s) as T2'),'table.id=T2.id', 'LEFT',NULL)
    ->get()->row();
    

    Don't forget to escape parameters in your subquery to avoid SQL Injection.

    0 讨论(0)
提交回复
热议问题