2013-04-03 42 views
1
SELECT 
    q1.user_id,q2.count,q2.total,q1.choice 
FROM  
    (
    SELECT 
     "table1"."user_id" as user_id,"table2"."choice" as choice 
    FROM 
     "table1", "table2" 
    WHERE 
     "table1"."user_id" = table2.ref_id     
    AND 
     "table1"."active" = 1 
    )q1 
LEFT OUTER JOIN   
    (
    SELECT 
     count(table1.*) as count, SUM(table2.add1) as total,table1.user_id as user_id 
    FROM 
     "table1", "table2" 
    WHERE     
     "table1"."type" = 1    
    AND 
     table1"."some_id" IN(SELECT user_id FROM "table2", "table3" WHERE "table3"."user_id" = table3.refid)     
    group by 
     "table2"."user_id" 
    )q2   
ON 
    q2.user_id=q1.user_id 
ORDER BY 
    q2.count ASC 

我有一個像這樣的查詢。它在db中工作正常。但不知道如何使用子查詢在codeigniter中編寫它。或者有沒有其他方法可以得到相同的結果?如何在代碼點火器中寫入連接選擇語句

回答

1

您可以使用$this->db->query()這個..

doc here

$sql='SELECT 
    q1.user_id,q2.count,q2.total,q1.choice 
FROM  
    (
    SELECT 
     "table1"."user_id" as user_id,"table2"."choice" as choice 
    FROM 
     "table1", "table2" 
    WHERE 
     "table1"."user_id" = table2.ref_id     
    AND 
     "table1"."active" = 1 
    )q1 
LEFT OUTER JOIN   
    (
    SELECT 
     count(table1.*) as count, SUM(table2.add1) as total,table1.user_id as user_id 
    FROM 
     "table1", "table2" 
    WHERE     
     "table1"."type" = 1    
    AND 
     table1"."some_id" IN(SELECT user_id FROM "table2", "table3" WHERE "table3"."user_id" = table3.refid)     
    group by 
     "table2"."user_id" 
    )q2   
ON 
    q2.user_id=q1.user_id 
ORDER BY 
    q2.count ASC'; 

$result=$this->db->query($sql); 
+0

和,你會使用這 - $> DB->查詢(),因爲CI的ActiveRecord的實現目前不支持子查詢。 – jcorry