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

このようなクエリが 1 つあります。db では正常に動作していますが、サブクエリを使用して codeigniter でこれを記述する方法がわかりません。または、同じ結果を得ることができる他の方法はありますか?

4

1 に答える 1

1

あなたは$this->db->query()これに使用することができます..

ここにドキュメント

$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);
于 2013-04-03T13:15:19.673 に答える