NTICompass / CodeIgniter-Subqueries

An active record subquery library for CodeIgniter. Also contains useful db helper functions.

Home Page:https://generic.computers.pictures

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

0 becomes null

caioiglesias opened this issue · comments

I'm doing some left joins involving "count", and when results are displayed zeros become null.

Can you show me the query you are running?

        $this->load->library('Subquery');

        $this->db->select('total.attendees, self.going, users.ack_id, users.first_name, events.venue, events.datetime, events.type, events.id');
        $this->db->join('users', 'events.user_id = users.user_id', 'left'); 
        $this->db->where('users.ack_id IN'. $ids); 
        $this->db->where('events.datetime > NOW()');    
        $sub = $this->subquery->start_subquery('join', 'left', 'events.id = self.event_id');
        $sub->select('user_id IS NOT NULL AS going, event_id')->from('attending')->where('user_id', $user_id);
        $this->subquery->end_subquery('self');      
        $sub2 = $this->subquery->start_subquery('join', 'left', 'events.id = total.event_id');
        $sub2->select('count(user_id) as attendees, event_id')->from('attending')->group_by("event_id");
        $this->subquery->end_subquery('total');
        $query = $this->db->get('events');

I'm getting null on total.attendees and self.going.

Are you sure this is a problem with the library? Do the subqueries (inside the joins) return the correct rows? Maybe the field is NULL because it's being LEFT JOINed?

Try running the query normally (without using Active Record), and make sure it's returning the correct data.

SELECT `total`.`attendees`, `self`.`going`, `users`.`ack_id`, `users`.`first_name`,
`events`.`venue`, `events`.`datetime`, `events`.`type`, `events`.`id`
FROM (`events`)
LEFT JOIN `users` ON `events`.`user_id` = `users`.`user_id`
LEFT JOIN (
  SELECT `user_id` IS NOT NULL AS going, `event_id`
  FROM (`attending`) WHERE `user_id` IS NULL
) AS self ON `events`.`id` = `self`.`event_id`
LEFT JOIN (
  SELECT count(user_id) as attendees, `event_id`
  FROM (`attending`) GROUP BY `event_id`
) AS total ON `events`.`id` = `total`.`event_id`
WHERE `users`.`ack_id` IN $ids
AND `events`.`datetime` > NOW()

I'm sorry, I was lacking proper sleep.

I had to use IFNULL() on the main query, not on the joins... :S

Your library rocks.

Sleep is overrated. We programmers don't need sleep! Anyway, I'm glad you solved your problem. :-)