Reputation: 134
I have 2 tables. One with a list of clients and another with a list of data. I am trying to create a table in my view that lists the client name along with the sum of a column(job_total) in the data table. I am able to write a query that works fine in most situations. The problem is, if I have not yet created a record in the data table I need to still display the client name with a balance of zero on my table in my view. Need some direction on how to handle this. I was thinking I need to query my list of clients and loop through that query just not sure how to do it.
I want my view to look like below:
+-------------+---------+ | Client Name | Balance | +-------------+---------+ | xxx | $75.00 | | xxx | $100.00 | | xxx | $0.00 | +-------------+---------+
Here is a rough layout of the two tables in my database:
cj_clients +----+-------------+ | id | client name | +----+-------------+ | 1 | client1 | | 2 | client2 | | x | xxx | +----+-------------+
cj_data +----+-----------+-----------+ | id | client_id | job_total | +----+-----------+-----------+ | 1 | 1 | 5.00 | | 2 | 1 | 10.00 | | 3 | 1 | 15.00 | +----+-----------+-----------+
The below code returns the desired results except when no entries have yet been made to the cj_data table. Not sure how to still get the client in the table view with a balance of $0.
$this->db->select('client_name,client_id, sum(job_total) AS balance')
->from('cj_data')
->join('cj_clients','cj_data.client_id = cj_clients.id')
->group_by('client_name');
return $this->db->get()->result();
Upvotes: 0
Views: 59
Reputation: 18567
You need to give left join
$this->db->select('client_name,client_id, IFNULL(sum(job_total),0) AS balance')
->from('cj_data')
->join('cj_clients','cj_data.client_id = cj_clients.id',"left") // here
->group_by('client_name');
return $this->db->get()->result();
I wrote IFNULL condition if record not found or it will show all data for all clients in cj_clients
Note: the Default behaviour of CodeIgniter is it will add inner join if join not specified
Upvotes: 1