简体   繁体   中英

Active Record - CodeIgniter : multiple COUNT on 3 joined tables

Working on a project with CodeIgniter and Active Record.

I face an issue with a query : I have 3 tables in my database which I would like not only to join but also to make countS on 2 of them. The tables are respectively linked with user_id, store_user_id, event_user_id fields

Table 1 : user user_id

Table 2 : store store_user_id

Table 3 : event event_user_id

What I am trying to do is to :

1 - Get all the data from user 2 - Count the number of stores with store_user_id = user_id (it may be 0) 3 - Count the number of events with event_user_id = user_id (it may be 0)

I have done this in my function :

    $this->db->select('*');
    $this->db->select('COUNT(s.store_user_id) as total_store', FALSE);
    $this->db->select('COUNT(e.event_user_id) as total_event', FALSE);
    $this->db->from('user u');
    $this->db->join('store s', 's.store_user_id = u.user_id', 'left'); // this joins the user table to store table
    $this->db->join('event e', 'e.event_user_id = u.user_id', 'left'); // this joins the user table to event table  
    $this->db->group_by('u.user_id');

    $q = $this->db->get();
    if ($q->num_rows()>0){
        foreach ($q->result() as $rows) {       
            $data[] = $rows;
        }

        return $data;
    }

The trouble is that when I display total_store and total_event in my view, the results are the same and I think figures are multiplied between them..

For example : For an user I have 3 events en 4 stores, the results displayed will be total_event = total_store = 12 ...

I don't understand why and it makes me crazy for hours!! Moreover, when I make only one count, the result is correct..

Any idea??

Many thanks in advance :)

Lastly I have implemented this basic SQL query :

$this->db->query('SELECT 
                u.*,
                x.total_store,
                y.total_event
            FROM 
            user u

            LEFT OUTER JOIN (SELECT s.store_user_id, COUNT(s.store_user_id) AS total_store
                FROM store s

                GROUP BY s.store_user_id) x ON x.store_user_id = u.user_id

            LEFT OUTER JOIN (SELECT e.event_user_id, COUNT(e.event_user_id) AS total_event  

            FROM event e

                GROUP BY e.event_user_id) y ON y.event_user_id = u.user_id
        ');

Hope it will helps others

When you count() you're counting the number of rows, not the number of distinct values in the result set. You're right that the number is being multiplied: there's a row in your resultset for each user-store-event combination.

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