【发布时间】:2026-01-09 17:00:02
【问题描述】:
我只剩下加入 4 个表来获得第一个表中存在的金额的总和。到目前为止,我已经尝试了许多替代方法来直接计算总和,但是如果我不使用 group_by,它要么变为 0(如果我使用 group_by),要么重复。这是我的代码:
$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 作为 $total 变量的值,而它应该是 288。
但是,当我删除 $this->db->group_by('cust_reservation_request.id'); 语句时,我在 attendees.attendees.cust_rid 上得到了重复,实际上它在那里,$total 变为 498,因为可能有多个参加者进行相同的摆脱。我想删除这个重复项,保留所有 Dollar_amount 字段的实际总和。
我的桌子是:
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”条件的情况下运行它
-
你可以在不处理框架的情况下在服务器上将它作为 SQL 查询运行吗?这样调试起来会更容易
-
嗨@IgorM 感谢您的回复。我已经尝试在服务器上运行它,当我添加 group_by 时它返回 0,并在使用 SUM 后返回重复的行。我也尝试使用 SELECT * 而不是 SUM 只是为了查看返回的结果,我知道它在那里返回了两次。
-
Hii @IgorM 我尝试在没有“WHERE cust_reservation_cancelled.rid IS NULL”的情况下运行查询,但结果保持不变。
-
在没有 COALESCE 和任何 WHERE 条件的情况下运行它。
标签: mysql sql codeigniter sum left-join