繁体   English   中英

如何在MySQL Codeigniter中显示最新的唯一记录

[英]How to display latest unique record in mysql codeigniter

假设我的表中有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

现在,当我对MySQL查询使用distinct时,我会检索:

    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"); 

如果要使用每个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

您期望的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

与活动记录是:

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

您可以使用group by子句按移动号码对值进行分组。 唯一关键字在这里不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM