我想从数据库限制中获取最近的记录仅为5.我使用下面的代码但没有工作。也许我错过了什么或者整个查询都是错的。请指导我。感谢
模型
public function get_comments ($id) {
$this->db->select('*');
$this->db->order_by('id', 'ASC');
$this->db->from('Item_comments');
$this->db->limit('5');
$this->db->where(array('checklist_item_id' => $id, 'status' => 1));
$query = $this->db->get();
return $query->result_array();
}
注意:查询工作正常,从db获取5条记录,但我想 将近期定位于底部。感谢
答案 0 :(得分:3)
要获得最后的结果,您需要按顺序排序
$this->db->order_by("id", "desc");
当然,您也可以使用其他列而不是ID。
以升序订购结果:
$this->db->order_by("id", "asc");
要反转生成的数组:
$results = get_comments();
$results = array_reverse($results);
或者如果您想在函数中执行此操作:
return array_reverse($query->result_array());
答案 1 :(得分:1)
试试这个
public function get_comments ($id) {
$sql = 'SELECT * FROM (SELECT Item_comments.id i_id,Item_comments.column_name1,Item_comments.column_name2 FROM Item_comments WHERE Item_comments.checklist_item_id = ' . $id . ' AND Item_comments.status = 1 ORDER BY Item_comments.id DESC LIMIT 5) T1 ORDER BY i_id ASC';
$query = $this->db->query($sql);
return $query->result_array();
}
答案 2 :(得分:1)
试试这个
function get_comments($start,$limit,$id)
{
$condition = array('checklist_item_id' => $id,'status'=>1);
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $start);
$query = $this->db->get_where('Item_comments',$condition);
$rows = $query->result();
return $rows;
}
答案 3 :(得分:0)
public function get_comments ($id) {
$this->db->select('*');
$this->db->order_by('id', 'DESC');
$this->db->from('Item_comments');
$this->db->limit('5');
$this->db->where(array('checklist_item_id' => $id, 'status' => 1));
$query = $this->db->get();
return $query->result_array();
}
答案 4 :(得分:0)
试试这个:
public function get_comments ($id) {
$this->db->select('*');
$this->db->order_by('id', 'DESC');
$this->db->from('Item_comments');
$this->db->limit('0,5');
$this->db->where(array('checklist_item_id' => $id, 'status' => 1));
$query = $this->db->get();
return $query->result_array();
}