我想运行一个查询来计算特定列的总和。为此,我需要加入两个表来映射匹配的记录并给出结果。下面我粘贴我的查询,请纠正我查询中的错误。它可能映射两次,所以它显示错误的结果。
$this->Inventory->find('all',array('joins'=>array(
array('table' => 'items',
'alias' => 'item',
'type' => 'left',
'conditions' => array(
'Inventory.item_id = item.id')
),
array('table' => 'material_owners',
'alias' => 'owner',
'type' => 'left',
'conditions' => array(
'Inventory.material_owner_id = owner.id')
),
array('table' => 'projects',
'alias' => 'project',
'type' => 'left',
'conditions' => array(
'Inventory.project_id = project.id')
),
array('table' => 'material_payments',
'alias' => 'mp',
'type' => 'left',
'conditions' => array(
'Inventory.material_owner_id=mp.material_owner_id'),
),
),
'conditions'=>array('Inventory.project_id'=>$project_id),
'fields' =>array('sum(Inventory.total_amount) as total_amount','sum(mp.paid_amount) as paid_amount','item.name','item.id','owner.id','owner.first_name','owner.last_name','project.id','project.name'),
'group'=> array('item.name','item.id','owner.id','owner.first_name','owner.last_name','project.name','project.id')
)
);
这是 cakephp 生成的结果查询。
SELECT sum("Inventory"."total_amount") as total_amount, sum("mp"."paid_amount") as paid_amount, "item"."name" AS "item__name", "item"."id" AS "item__id", "owner"."id" AS "owner__id", "owner"."first_name" AS "owner__first_name", "owner"."last_name" AS "owner__last_name", "project"."id" AS "project__id", "project"."name" AS "project__name" FROM "inventories" AS "Inventory" left JOIN "items" AS "item" ON ("Inventory"."item_id" = "item"."id") left JOIN "material_owners" AS "owner" ON ("Inventory"."material_owner_id" = "owner"."id") left JOIN "projects" AS "project" ON ("Inventory"."project_id" = "project"."id") left JOIN "material_payments" AS "mp" ON ("Inventory"."material_owner_id" = "mp"."material_owner_id") LEFT JOIN "items" AS "Item" ON ("Inventory"."item_id" = "Item"."id") LEFT JOIN "units" AS "Unit" ON ("Inventory"."unit_id" = "Unit"."id") LEFT JOIN "projects" AS "Project" ON ("Inventory"."project_id" = "Project"."id") LEFT JOIN "material_owners" AS "MaterialOwner" ON ("Inventory"."project_id" = "MaterialOwner"."id") WHERE "Inventory"."project_id" = '4' GROUP BY "item"."name", "item"."id", "owner"."id", "owner"."first_name", "owner"."last_name", "project"."name", "project"."id"