CodeIgniter query builder (query builder) - subqueries

Need for the subquery recent development project, after some research the outcome:

<?php
// Sub Query
$this->db->select('*');
$this->db->from('TableB');
$subQuery = $this->db->get_compiled_select();

// Main Query
$this->db->select('*');
$this->db->from('TableA');
$this->db->join("($subQuery) AS TableB", 'TableA.id = TableB.a_id');
$r = $this->db->get();
return $r->result_array();
?>

There is also a case where found:
TableA TableB the JOIN on the LEFT = TableB.a_id TableA.id, if there are restrictions TableB (. Ex WHERE TableB.age> 15) , requires the use of subqueries priority or setting conditions on the filter and then join, otherwise it will turn into Inner Join.

-- 变成Inner Join
Select * 
From TableA 
Left Join TableB on TableA.id = TableB.a_id
Where
     TableB.age > 15

-- Left Join正确的结果
Select * 
From TableA 
Left Join 
       (Select * 
        From TableB 
        where TableB.age > 15) 
     AS TableB on TableA.id = TableB.a_id
  
-- 在on先对右表做过滤,再join
Select * 
From TableA 
Left Join TableB on 
     TableA.id = TableB.a_id 
     and TableB.age > 15
Published 18 original articles · won praise 1 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_42557486/article/details/83584656