【问题标题】:Codeigniter Group by last recordCodeigniter 按最后一条记录分组
【发布时间】:2016-05-31 03:31:04
【问题描述】:

假设我有 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'); 

【问题讨论】:

    标签: codeigniter


    【解决方案1】:

    使用子查询。见下面代码

    $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'); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 2016-02-14
      相关资源
      最近更新 更多