我想找到这两个表的总和

时间:2019-08-22 16:20:24

标签: mysql codeigniter

我想找到这两个表的总和

请帮助我解决此问题

表1

id  |  pr_id  |  cl_one
========================
 1  |    2    |   500
------------------------
 2  |    2    |   500

表2

id  |  pr_id  |   cl2
======================
 1  |    2    |   500

codeigniter查询

$this->db->select('SUM(s.cl_one)+SUM(l.cl2) AS total_amount, COUNT(s.cl_one)+SUM(l.cl2) AS total_counts')
                      ->from('Table1 AS s')
                      ->join('Table2 AS l', 's.pr_id = l.pr_id')
                      ->get()->row();

结果

total_amount = 2000;

total_counts = 4;

我需要这样的结果

total_amount = 1500;

total_count = 3;

3 个答案:

答案 0 :(得分:0)

之所以得到2000,是因为当您将table2中的一行连接到table1中的两行时,来自t2的单行将自身进行复制以匹配来自t1的两行。然后,如果您对重复的行求和,您又添加了500

解决这些问题的最简单方法是在加入它们之前对它们进行分组和汇总:

SELECT t1.sum + t2.sum as total
FROM
  (SELECT pr_id, sum(cl_one) as sum FROM table1 GROUP BY pr_id) t1    
  INNER JOIN 
  (SELECT pr_id, sum(cl_2) as sum FROM table2 GROUP BY pr_id) t2    
  ON t1.pr_id = t2.pr_id

这样,t1的一行与t2的一行匹配,所以不会重复... 但是我不知道您将如何在codeigniter /您使用的任何ORM中执行此操作,但是我希望这可以帮助/轻松翻译

答案 1 :(得分:0)

最终做到了……

一个简单的查询即可解决此问题

SELECT pr_id, SUM(sum_v) AS total_amount, COUNT(sum_v) AS total_counts FROM( 
SELECT pr_id, cl_one AS sum_v FROM table1  UNION ALL 
SELECT pr_id, cl2 AS sum_v FROM table2)x GROUP BY pr_id

答案 2 :(得分:0)

Codeigniter查询:

public async Task<ActionResult> UploadImage()
        {
            IFormFile formFile;
            formFile= Request.Form.Files[0];
            if (formFile == null)
                return Json(new { location = "Not Found" });
....
}