db->join('table2 b', 'a.b_PID = b.PID', 'LE-6ren">
gpt4 book ai didi

php - 左连接列不存在时如何选择总和

转载 作者:行者123 更新时间:2023-11-29 05:08:25 25 4
gpt4 key购买 nike

$this->db->select("a.*, SUM(b.amount) as total");
$this->db->join('table2 b', 'a.b_PID = b.PID', 'LEFT');
$this->db->from(table1 a');
$query = $this->db->get();
$result = $query->result();

在我上面的查询中,我将表 b 连接到 b_PID 上的表,但是并非表 a 中的所有记录都在表 b 中有记录,因此如果我选择 SUM 表 b 中的金额如上所述,记录没有数据不返回表 b 中的值。如果表 b 中没有记录,如何选择 sum b.amount 并将金额返回为 0?由于某些原因,我无法使用 group_by。

提前谢谢你。

最佳答案

您应该使用COALESCE

  SELECT d.*
, IFNULL(SUM(a.total),0) AS total
FROM ( SELECT * FROM table2 b) d
LEFT JOIN table1 a
a.b_PID = b.PID

关于php - 左连接列不存在时如何选择总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44015950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com