加入 2 个表并在 codeigniter 中按条件求和

Join 2 tables and sum with condition in codeigniter

我有 2 table

Table1: customers:
-------------
| id | name |
-------------
| 1  | Mark |
-------------
| 2  | Tom |
-------------
| 3  | John |

Table2: sales:
-----------------------------------
|sid | customerid | price | state | 
-----------------------------------
| 10 | 1          | 12000 | 0     | 
-----------------------------------
| 11 | 2          | 13500 | 1     | 
-----------------------------------
| 12 | 2          | 23000 | 1     | 
-----------------------------------
| 13 | 3          | 26000 | 0     | 
-----------------------------------
| 14 | 1          | 66000 | 1     | 
-----------------------------------

the state column is 0=no dep  and 1=dept

我想通过在销售 table 中检查他们来列出拥有 DEPT 的客户。现在我正在循环访问客户并一一检查。它有效!但是当客户 table 中的行数增加时,页面速度变慢。我想通过 SQL 查询来实现。有人可以帮我吗?

结果会是这样的:

Mark  66000
Tom   36500

您可以在销售 table 中简单地按客户 ID 分组。代码会是这样

return $this->db->select('MAX(customers.name) AS name, SUM(sales.price) as price')->join('sales', 'sales.customerid = customers.id')->where('sales.state', 1)->group_by('customers.id')->get('customers')->result();

通过以下查询,您将获得与您想要的相同的输出。表的连接将使用 where condition

在过滤后的数据上执行
$this->db->select('customers.name,sum(sales.price)')
->from('customers')
->join('sales','sales.customerid = customers.id','left')
->where('sales.state !=0')
->group_by('customers.name');
->get()->result_array();