【问题标题】:How to display latest unique record in mysql codeigniter如何在mysql codeigniter中显示最新的唯一记录
【发布时间】:2016-11-25 07:39:53
【问题描述】:

假设我的表中有 6 条记录

    id |       mobile_no  |     date
-------------------------------------------        
    1  |       9999999999 |   11-11-2016

    2  |       8888888888 |   12-11-2016

    3  |       9999999999 |   13-11-2016

    4  |       9999999999 |   16-11-2016

    5  |       8888888888 |   20-11-2016

    6  |       8888888888 |   22-11-2016

现在当我使用 distinct 和 mysql 查询时,我会检索:-

    id |       mobile_no  |     date
-------------------------------------------    
    1  |       9999999999 |   11-11-2016

    2  |       8888888888 |   12-11-2016

虽然我想检索:-

    id |       mobile_no  |     date
-------------------------------------------    
    4  |       9999999999 |   16-11-2016

    6  |       8888888888 |   22-11-2016

请帮我在codeigniter mysql中使用什么查询来访问上面的记录?

下面是我的模型查询-

    $this->db->select('*');

     $this->db->from('miscall_records'); 

    $this->db->distinct(); 

    $this->db->group_by('mobnos');

     $this->db->order_by("id", "desc"); 

【问题讨论】:

  • 好吧 - 你能包括有问题的查询吗?恐怕我无法通过心灵感应调试。
  • 不作为评论。 编辑您的问题以包含更多信息
  • 不确定如何在 CI 上完成,但 sql 应该是这里dev.mysql.com/doc/refman/5.7/en/…中的模式@
  • 建议:GROUP BY不以任何方式对返回哪些数据集做出任何保证 - 它应该始终与聚合函数。在你的情况下,DISTINCT 与它无关。
  • 它在获取记录时简单地使用 MAX(date)

标签: php mysql codeigniter unique distinct


【解决方案1】:

如果您想分别使用 ID 最高的数据集,则必须使用不同的方法。
您必须首先通过 GROUP BY 和相应的聚合函数 MAX 为每个数字选择最高的 ID,然后在这些键上加入表本身。

SELECT values.* FROM
(SELECT MAX(id) AS id FROM miscall_records GROUP BY mobile_no) AS keys
LEFT JOIN miscall_records AS values
ON keys.id = values.id

【讨论】:

    【解决方案2】:

    您预期的 sql 查询是:

    select a.id, a.mobile_no, a.date from miscall_records a
    where a.id = (select max(b.id) from miscall_records b 
    where b.mobile_no = a.mobile_no) group by a.mobile_no
    

    使用 Active Records 是:

    $this->db->select('a.id, a.mobile_no, a.date');
    $this->db->from('miscall_records a');
    $this->db->where('a.id = (select max(b.id) from miscall_records b where b.mobile_no = a.mobile_no)'); 
    $this->db->group_by('a.mobile_no');    
    $query = $this->db->get(); 
    

    或者只使用max

    select max(a.id), a.mobile_no, a.date from miscall_records a group by a.mobile_no
    

    活动记录:

    $this->db->select('max(a.id), a.mobile_no, a.date');
    $this->db->from('miscall_records a'); 
    $this->db->group_by('a.mobile_no');    
    $query = $this->db->get();
    

    【讨论】:

      【解决方案3】:

      您可以使用 group by 子句按手机号对值进行分组。 distinct 关键字在这里不起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-27
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多