codeigniter活动记录获取最后10条记录并对ASC进行排序

时间:2012-08-08 12:41:26

标签: codeigniter activerecord

我想知道这个SQL语句是否在Codeigniter活动记录中完成。

SELECT * FROM (
SELECT * 
FROM chat 
WHERE (userID = $session AND toID = $friendID) 
OR (userID = $friendID AND toID = $session)  
ORDER BY id DESC
LIMIT 10
) AS `table` ORDER by id ASC

3 个答案:

答案 0 :(得分:6)

您必须使用活动记录类的_compile_select()_reset_select()方法。

$this->db->select('*');
$this->db->from('chat');
$this->db->where("(userID='{$session}' AND toID='{$friendID}')");
$this->db->or_where("(userID='{$friendID}' AND toID='{$session}')");
$this->db->order_by('id', 'DESC');
$this->db->limit('10');

$subQuery = $this->db->_compile_select();

$this->db->_reset_select();

$this->db->select('*');
$this->db->from("{$subQuery} AS table");
$this->db->order_by('id', 'ASC');

$query = $this->db->get();

不幸的是,在CI 2.0+中,_compile_select()_reset_select()是受保护的方法。游民。在扩展数据库驱动程序时,您必须遵循this tutorial,您可以在其中编写如下方法:

function get_compiled_select()
{
    return $this->db->_compile_select();
}

function do_reset_select()
{
    $this->db->_reset_select();
}

我想花点时间指出,这种类型的行动会更好地通过联接来实现。您应该考虑更改数据库结构,以便可以高效地进行连接。

答案 1 :(得分:1)

这可行,但不是主动记录变体。

$this->db->query( "SELECT * FROM (
     SELECT * 
     FROM chat 
     WHERE (userID = ? AND toID = ?) 
     OR (userID = ? AND toID = ?)  
     ORDER BY id DESC
     LIMIT 10
     ) AS `table` ORDER by id ASC", array( $session, $friendID, $friendID, $session) );"

答案 2 :(得分:0)

您可以将查询用作:

$this->db->select('SELECT * 
     FROM chat 
     WHERE (userID = $session AND toID = $friendID) 
     OR (userID = $friendID AND toID = $session)  
     ORDER BY id DESC
     LIMIT 10') AS `table` ORDER by id ASC', FALSE);