简体   繁体   English

用join codeigniter进行求和查询

[英]Summation Query with join codeigniter

I have 2 tables. 我有2张桌子。 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. 我试图在我的视图中创建一个表,该表列出客户端名称以及数据表中列(job_total)的总和。 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. 下面的代码返回所需的结果,除非尚未对cj_data表进行任何输入。 Not sure how to still get the client in the table view with a balance of $0. 不确定如何仍以$ 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();

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 如果未找到记录,我写了IFNULL条件,否则它将显示cj_clients中所有客户端的所有数据

Note: the Default behaviour of CodeIgniter is it will add inner join if join not specified 注意:CodeIgniter的默认行为是,如果未指定连接,它将添加内部连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM