3

我想知道这个 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
4

3 回答 3

9

您必须使用活动记录类的_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()是受保护的方法。真可惜。您必须按照本教程扩展 DB 驱动程序,您可以在其中编写如下方法:

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

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

我想花点时间指出,这种类型的操作会更好地由连接服务。您应该考虑更改您的数据库结构,以使连接成为可能且高效。

于 2012-08-08T13:35:38.950 回答
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) );"
于 2012-08-08T13:24:41.257 回答
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); 
于 2012-08-08T12:58:58.713 回答