我正在尝试运行包含三个表的SQL语句。
收入
-id
-title
-amount
-company_id
公司
-id
-name
-sector_id
扇区
-id
-name
你可以看到'收入'表与'部门没有直接关系。表。我想做的是通过IndustrySectors获得总收入。
到目前为止,我已经设法计算了两个表,但知识限制为三个。请指导我。
这是两张桌子。按公司收入
$x=0;
foreach($companies as $Company){
$companyName= $Company['Company']['name'];
$companyId= $Company['Company']['id'];
$query= $this->Income->query("
SELECT SUM( amount ) AS IncomeTotal
FROM incomes
WHERE company_id=$companyId
");
$total=$query[0][0]['IncomeTotal'];
if($total!=null){
//$incomeByCompany[$companyName]=$total;
//$incomeByCompany['total']=$total;
$incomeByCompany[$x]['companyId']=$companyId;
$incomeByCompany[$x]['name']=$companyName;
$incomeByCompany[$x]['total']=$total;
}
$x++;
}
答案 0 :(得分:1)
SELECT s.name , SUM(i.amount) as total_sector
FROM sectors s
JOIN companies c
ON s.id = c.sector_id
JOIN incomes i
ON c.id = i.company_id
GROUP BY s.name
除了循环外,您的公司查询应该是:
SELECT c.name , SUM(i.amount) as total_sector
FROM companies c
ON s.id = c.sector_id
JOIN incomes i
ON c.id = i.company_id
GROUP BY c.name