【问题标题】:Join 2 tables and sum with condition in codeigniter加入 2 个表并在 codeigniter 中对条件求和
【发布时间】:2021-11-24 03:51:40
【问题描述】:

我有两张桌子

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

我想通过在销售表中检查他们来列出拥有 DEPT 的客户。现在我正在循环客户并一一检查。它有效!但是当客户表中的行数增加时,页面会变慢。我想通过 SQL 查询来做到这一点。谁能帮帮我?

结果会是这样的:

Mark  66000
Tom   36500

【问题讨论】:

    标签: mysql database codeigniter codeigniter-3


    【解决方案1】:

    通过以下查询,您将获得与您想要的相同的输出。将使用 where 条件对过滤后的数据执行表的连接

    $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();
    

    【讨论】:

      【解决方案2】:

      您可以简单地按销售表中的客户 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();
      

      【讨论】:

        猜你喜欢
        • 2013-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-06
        • 2015-10-05
        • 2012-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多