假设我有3或4个表,其中一些表与父表连接。我想按最后记录显示小组。
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 |
但是当我按照tagid查询分组时,它将检索第一行
--------------------------------------------------------------------
| 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 :(得分: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');