如何按id升序选择最后5行 - CakePHP

时间:2014-12-14 12:16:15

标签: mysql cakephp

我希望通过升序获得最后5个记录顺序。

我有一个表名chat_public_msgs我已经插入了6个Sample数据。我需要id asc的最后5个记录顺序。请查看以下内容。

chat_public_msgs -

id  username  message  created
1    smith   hi        2014-12-14 10:14:15   
2    piter   hello     2014-12-14 10:14:20    
3    john    hi smith  2014-12-14 10:14:28
4    raj     aaa       2014-12-14 10:15:22
5   chinu    test      2014-12-14 10:15:25  
6   piter    bbbbb     2014-12-14 10:15:40  

查询 -

$fields = array('ChatPublicMsg.message','ChatPublicMsg.created','ChatPublicMsg.username');
$results = $this->ChatPublicMsg->find('all',array(
           'fields'=>$fields,
           'limit'=>5, 
           'order'=>array('ChatPublicMsg.id ASC')));

输出 -

id  username  message  created
1    smith   hi        2014-12-14 10:14:15   
2    piter   hello     2014-12-14 10:14:20    
3    john    hi smith  2014-12-14 10:14:28
4    raj     aaa       2014-12-14 10:15:22
5   chinu    test      2014-12-14 10:15:25

但我想要这个 -

id  username  message  created  
2    piter   hello     2014-12-14 10:14:20    
3    john    hi smith  2014-12-14 10:14:28
4    raj     aaa       2014-12-14 10:15:22
5   chinu    test      2014-12-14 10:15:25  
6   piter    bbbbb     2014-12-14 10:15:40  

编辑 -

我从Select last 20 order by ascending - PHP/MySQL

收到了此查询
select * from (
    select * from chat_public_msgs order by id desc limit 5
) tmp order by tmp.id asc

如何以CakePhp格式编写上述查询?

1 个答案:

答案 0 :(得分:5)

您可以通过按' id'对结果进行排序来执行此操作。 DESC并将记录数限制为5.然后使用array_reverse()来反转排序。

$fields = array('ChatPublicMsg.message','ChatPublicMsg.created','ChatPublicMsg.username');
$results = $this->ChatPublicMsg->find('all',array(
       'fields'=>$fields,
       'limit'=>5, 
       'order'=>array('ChatPublicMsg.id DESC')));
$reverse = array_reverse($results['ChatPublicMsg']);
$results['ChatPublicMsg'] = $reverse;

这假设' id'随每条记录递增。否则,您需要向表中添加时间戳字段,并使用此字段进行排序。

相关问题