简体   繁体   中英

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...???

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM