我想通过升序得到最后5个记录顺序。
我有一个表名chat_public_msgs我插入了6个示例数据。我需要最后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格式编写上述查询?

最佳答案

可以通过按“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”随每条记录递增。否则,需要向表中添加时间戳字段并使用此字段进行排序。

关于mysql - 如何按ID升序选择最后5行的顺序-CakePHP,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27469181/

10-11 01:22