I have an application that basically simulates a locker. Inside each locker I have N racks. Inside each rack I have N boxes, N folders and N books. Some of this objects are not acessible (they have an boolean attribute called ACESSIBLE).
I want to show each locker and the sum of objects ordering by type (book, folder and box). Something like:
RACK_ID: 1
RACK_NUMBER: 001
LOCKER_NUMBER: 54
SUM_BOXES: 10
SUM_FOLDERS: 20
SUM_BOOKS: 10
My query:
$this->db->select('r.ID AS RACK_ID, r.NUMBER AS RACK_NUMBER, l.NUMBER AS LOCKER_NUMBER) ->select('IFNULL(COUNT(DISTINCT `box`.`ID`), 0) AS `SUM_BOXES`', FALSE) ->select('IFNULL(COUNT(DISTINCT `book`.`ID`), 0) AS `SUM_BOOKS`', FALSE) ->select('IFNULL(COUNT(DISTINCT `folder`.`ID`), 0) AS `SUM_FOLDERS`', FALSE); $this->db->from('rack r'); $this->db->join('locker l', 'l.ID = r.LOCKER_fk', 'inner'); $this->db->join('box box', 'box.RACK_fk = r.ID', 'left'); $this->db->join('book book', 'book.RACK_fk = r.ID', 'left'); $this->db->join('folder folder', 'folder.RACK_fk = r.ID', 'left'); $this->db->where('r.LOCKER_fk', $this->session->userdata('LOCKER_ID')); $this->db->group_by("r.ID");
This works fine, but the count returns all boxes, books and folders from each rack, ACESSIBLE OR NOT. I want to input a WHERE condition on each count that returns only acessible objetcs (something like WHERE boxes.ACESSIBLE = 1). How can I do that?
Thanks.
EDIT: Ok so I found a solution: changing to this:
$this->db->join('box box', 'box.RACK_fk = r.ID AND box.ACESSIBLE= "1"', 'left');
$this->db->join('book book', 'book.RACK_fk = r.ID AND book.ACESSIBLE= "1"', 'left');
$this->db->join('folder folder', 'folder.RACK_fk = r.ID AND folder.ACESSIBLE= "1"', 'left');