I'm using PHP CodeIgniter to query from my Database. I need to use multiple LEFT OUTER joins. The join uses multiple conditions (I'm not sure it is supported as of the bug). My query results have the same value for both parameters I want to fetch:
Query:
$this->db->select('anonymous.*,
count(items_likes.id) as all_likes, count(items_comments.id) as all_comments');
$this->db->from('anonymous');
$this->db->where('anonymous.fid', $feed_id);
$this->db->group_by('anonymous.id');
$this->db->join('all_users', 'all_users.id = anonymous.uid', 'left outer');
$this->db->join('images', 'images.ud = anonymous.uid AND images.fid = anonymous.fid', 'left outer');
$this->db->join('items_likes', 'items_likes.uid = anonymous.uid AND items_likes.fid = anonymous.fid', 'left outer');
$this->db->join('items_comments', 'items_comments.uid = anonymous.uid AND items_comments.fid = anonymous.fid', 'left outer');
$list = $this->db->get()->result();
anonymous: is a table with unregistered users
fid: Is the feed id
images: Is a table of all the images that were uploaded to the feed
items_likes: Is all the users' likes per image
items_comments: Is all the users' comments per image
The problem is that all_comments always return the same value as all_likes. I'm not sure if the multiple LEFT-OUTER joins are the problem or maybe the fact that I'm using multiple conditions in every join statement i.e.
items_comments.uid = anonymous.uid AND items_comments.fid = anonymous.fid
The log result:
"all_likes":"12","all_comments":"12"
although I have 12 likes, the comments should be 3
If I write the query as follows the result is ok:
$this->db->select('anonymous.*,
(SELECT count( items_likes.id ) FROM items_likes WHERE items_likes.uid = anonymous.uid AND items_likes.fid = anonymous.fid) as all_likes,
(SELECT count( items_comments.id ) FROM items_comments WHERE items_comments.uid = anonymous.uid AND items_comments.fid = anonymous.fid) as all_comments');
$this->db->from('anonymous');
$this->db->where('anonymous.fid', $feed_id);
$this->db->group_by('anonymous.id');
$this->db->join('all_users', 'all_users.id = anonymous.uid', 'left outer');
$this->db->join('images', 'images.ud = anonymous.uid AND images.fid = anonymous.fid', 'left outer');
//$this->db->join('items_likes', 'items_likes.uid = anonymous.uid AND items_likes.fid = anonymous.fid', 'left outer');
//$this->db->join('items_comments', 'items_comments.uid = anonymous.uid AND items_comments.fid = anonymous.fid', 'left outer');
$list = $this->db->get()->result();