2016-05-31 63 views
0

說我有3或4表,其中一些表與父表連接。我想按最後一個記錄顯示組。Codeigniter Group最後紀錄

Table: table1 
-------------------------------------------------------------------- 
| table1Id(AI)(PK) | date  | tagid | blah3 | blah3 | blah4 | 
-------------------------------------------------------------------- 
1     | 2016-05-01 | 101 | 
2     | 2016-05-04 | 102 | 
3     | 2016-05-10 | 101 | 
4     | 2016-05-15 | 101 | 
5     | 2016-05-04 | 103 | 
6     | 2016-05-20 | 101 | 

但是當我通過標籤識別做查詢組會檢索第一行

-------------------------------------------------------------------- 
| table1Id(AI)(PK) | date  | tagid | blah3 | blah3 | blah4 | 
-------------------------------------------------------------------- 
1     | 2016-05-04 | 101 | 
2     | 2016-05-04 | 102 | 
5     | 2016-05-04 | 103 | 

我想看看這樣

-------------------------------------------------------------------- 
| table1Id(AI)(PK) | date  | tagid | blah3 | blah3 | blah4 | 
-------------------------------------------------------------------- 
6     | 2016-05-20 | 101 | 
2     | 2016-05-04 | 102 | 
5     | 2016-05-04 | 103 | 

我這樣的查詢

$this->db->select('*'); 
$this->db->from('tablename1'); 
$this->db->join('tablename2', 'tablename2.tagid= tablename1.tagid', 'left'); 
$this->db->group_by('tablename1.tagId, tablename2.tagId'); 
$this->db->order_by('tablename1.tagId','asc'); 
什麼

回答

0

使用子查詢。見下面的代碼

$this->db->select('*'); 
$this->db->from('tablename1'); 
$this->db->order_by('table1Id','DESC'); 
$subquery = $this->db->get_compiled_select(); 

$this->db->select('*'); 
$this->db->from('('.$subquery.') a'); 
$this->db->join('tablename2', 'tablename2.tagid= a.tagid', 'left'); 
$this->db->group_by('a.tagId, tablename2.tagId'); 
$this->db->order_by('a.tagId','asc');