Reputation: 21
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 :)
Upvotes: 0
Views: 2584
Reputation: 21
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
Upvotes: 2
Reputation: 615
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.
Upvotes: 1