我將加入4個表以獲取第一個表中存在的金額的總和。到目前爲止,我已經嘗試了很多方法來直接獲得總和,但是如果我不使用group_by,它會變成0(如果我是group_by),或者是重複的。這裏是我的代碼:Codeigniter SUM和LEFT JOIN刪除重複項
$this->db->select('COALESCE(SUM(cust_ reservation_request.dollar_amount), "0") as total');
$this->db->join('cust_ reservation_request', 'cust_ reservation_request.id = cust_reservations.rid', 'LEFT');
$this->db->join('attendees', 'cust_rid= cust_ reservation_request.id', 'LEFT');
$this->db->join('cust_reservation_cancelled', 'cust_reservation_cancelled.rid = cust_ reservation_request.id', 'LEFT');
$this->db->where('cust_ reservation_request.tid IN (5, 6, 7, 8)->where('attendees.status', 1)->where('cust_reservation_cancelled.rid IS NULL');
$this->db->group_by('cust_reservation_request.id');
$total = $this->db->get('cust_reservations')->row()->total;
我得到0爲$總變量的值,而應該是288 然而,當我刪除$this->db->group_by('cust_reservation_request.id');
聲明,我得到重複上attendees.attendees.cust_rid
,這實際上是在那裏, $ total變爲498,因爲可能有多個參與者爲同一個擺脫。我想刪除這個重複的,保留所有dollar_amount字段的實際SUM。
我的表是:
cust_ reservation_request
id // index, foreign key in rest of other tables
tid
uid
dollar_amount
cust_reservations
id
rid // related to id in cust_ reservation_request table
reservation_date
pay_token
cust_ reservation_cancelled
id
rid // related to cust_ reservation_request.id
cancel_date
attendees
id
cust_rid // its the same rid, related to cust_reservation_request.id
status
你認爲有可能做到這一點任何安全的方式,刪除重複,同時以適當的方式做SUM?
非常感謝您的幫助。
嘗試運行它沒有「WHERE cust_reservation_cancelled.rid IS NULL」條件 – IgorM
你可以運行它作爲服務器上的SQL查詢而不處理框架?這樣可以更容易地調試 – IgorM
Hi @IgorM感謝您的回覆。我已經試過它在服務器上運行,它在我添加group_by時返回0,並且在使用SUM之後返回重複的行。我也嘗試使用SELECT *而不是SUM來查看返回的結果,並且在那裏我知道它會返回一行兩次。 – Zafar