我有2張桌子
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
uj5u.com熱心網友回復:
通過以下查詢,您將獲得所需的相同輸出。表的連接將使用 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();
uj5u.com熱心網友回復:
您可以簡單地按銷售表中的客戶 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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326054.html
標籤:mysql 数据库 代码点火器 codeigniter-3
上一篇:如何拆分字串并向其添加額外的字串
