Mysql 如何按id升序选择最后5行-CakePHP
我想通过升序获得最后5条记录 我有一个表名Mysql 如何按id升序选择最后5行-CakePHP,mysql,cakephp,Mysql,Cakephp,我想通过升序获得最后5条记录 我有一个表名chat\u public\u msgs我插入了6个示例数据。我需要最后5个记录按id asc排序。请在下面查看 表chat\u public\u 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 20
chat\u public\u msgs
我插入了6个示例数据。我需要最后5个记录按id asc排序。请在下面查看
表chat\u public\u 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
编辑-
我是从你那里得到这个问题的
如何以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”随每条记录递增。否则,您需要将时间戳字段添加到表中,并使用此字段进行排序。您可以通过按“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”随每条记录递增。否则,您需要向表中添加时间戳字段,并使用此字段进行排序