如何使用联接表按组检索记录取​​决于MAX?

时间:2019-03-10 05:07:38

标签: php codeigniter codeigniter-3 codeigniter-2

这是我在模型中的查询

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

1 个答案:

答案 0 :(得分: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的条件添加到相应的表中。

也许是这样,我还没有测试

更新

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');