2014-03-04 28 views
0
select 
    x1.category 
    , x1.title 
from yourtable x1 
where 
    (
    select count(*) 
    from yourtable x2 
    where x2.category = x1.category 
    and x2.title <= x1.title 
    ) <= 2 
order by category, title; 

我在我的模型中有這樣的東西。如何將Sql代碼轉換爲codeigniter語法?

$this->db->select('x1.category','x1.title, false); 
     $this->db->from('yourtable as x1'); 
     $sub = $this->subquery->start_subquery('where'); 
     $sub ->select('count(*) ')<=25; 
     $sub ->from('yourtable as x2'); 
     $sub ->where('x2.category = x1.category and x2.title<= x1.title'); 
     $this->subquery->end_subquery('count(*)'); 
     $this->db->order_by('category','title','RANDOM'); 
     $query = $this->db->get('yourtable'); 

而且我收到錯誤

Fatal error: Call to a member function start_subquery() on a non-object in ....

回答

0

您將需要設置的子查詢笨:

http://labs.nticompassinc.com/CodeIgniter-Subqueries/

此外,你可以做:

$this->db->select('x1.category','x1.title', false); 
$this->db->from('yourtable as x1'); 
$this->db->where('(SELECT count(*) FROM yourtable x2 WHERE x2.category = x1.category AND x2.title <= x1.title) <= 2', NULL, false); 
$this->db->order_by('category','title');