如何使用连接表检索组中的记录取决于MAX?

问题描述 投票:0回答:1

这是我在模型中的查询:

return $this->db->join('tbl_customer', 'tbl_customer.cus_code = tbl_cus_account.custcode')
                ->where("status", 1)
                ->where("DATE_FORMAT(nextbillingdate,'%Y-%m') <= ", date('Y-m'))
                ->select('*,MAX(issuewithmain) AS issuewithmain, SUM(monthlyfee) AS monthlyfee, count(accountcode) as rows')
                ->group_by('custcode')
                ->get('tbl_cus_account');
  • 以下是我的连接查询表:enter image description here enter image description here

- 我想要的结果如下图所示:enter image description here

php codeigniter codeigniter-3 codeigniter-2
1个回答
0
投票

您的查询可能是这样的

SELECT t.*, t2.rows, t2.monthlyfee from tbl_cus_account t join (SELECT MAX(issuewithmain) AS issuewithmain, custcode, count(accountcode) as rows, SUM(monthlyfee) AS monthlyfee from tbl_cus_account JOIN tbl_customer ON tbl_customer.cus_code = tbl_cus_account.custcode  where status = 1 AND DATE_FORMAT(nextbillingdate,"%Y-%m") <= DATE_FORMAT(now(),"%Y-%m") GROUP BY custcode) t2 on t.issuewithmain = t2.issuewithmain and t.custcode = t2.custcode

在这里,你对同一个表进行了额外的连接,只获得与你的max(issuewithmain)匹配的确切记录

您需要将此查询转换为codeigniter并将where的条件添加到相应的表中。

也许是这样的,我没有测试过

UPDATE

return $this->db->join('(SELECT MAX(issuewithmain) AS issuewithmain, custcode, count(accountcode) as rows, SUM(monthlyfee) AS monthlyfee from tbl_cus_account where status = 1 AND DATE_FORMAT(nextbillingdate,"%Y-%m") <= "'.date('Y-m').'" GROUP BY custcode) t2', 'tbl_cus_account.issuewithmain = t2.issuewithmain AND t2.custcode = tbl_cus_account.custcode')->select('tbl_cus_account.*, t2.monthlyfee, t2.rows') ->join('tbl_customer', 'tbl_customer.cus_code = t2.custcode') ->group_by('t2.custcode') ->get('tbl_cus_account'); 
© www.soinside.com 2019 - 2024. All rights reserved.