VishnuPrasad
VishnuPrasad

Reputation: 1078

subquery where condition from different table in codeigniter

By using subquery library function how is it possible to select a record that matches the condition from both tables in subquery...?

Here is the actual sql query

SELECT *, (SELECT count('report_id') 
           FROM report 
           WHERE report.category = category.cat_id 
                 and report.user_id IN (68, 69, 70)) AS cnt 
FROM (`category`)

I need the equivalent in codeigniter as:

    $this->db->select('*')->from('category');
    $sub = $this->subquery->start_subquery('select');
    $sub->select("count('report_id')")->from('report')
        ->where_in(array('user_id'=>(68, 69, 70)));
    $this->subquery->end_subquery('number'); 

In this how can i put my second condition...???

Upvotes: 2

Views: 1674

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

By the way is there a really need of dependent sub query this will only increase the load and it will be executed for each row in category table,You can write equivalent join query as

SELECT c.*, 
COUNT(DISTINCT r.report_id) AS cnt /*you can omit distinct if you have unique report ids  */
FROM `category` c
LEFT JOIN report r ON r.category = c.cat_id AND r.user_id IN (68, 69, 70)
GROUP BY c.cat_id

And active record query as

$result = $this->db->select('c.*,COUNT(DISTINCT r.report_id) AS cnt ',FALSE)
    ->from('category c')
    ->join('report r','r.category = c.cat_id AND r.user_id IN (68, 69, 70)','LEFT')
    ->group_by('c.cat_id')
    ->get()
    ->result();

Upvotes: 3

Related Questions