0

我在下面有这个连接查询。我有一个问题。shipUnits 列出现错误。它只计算总项目。问题是我正在计算两组对象,除了发货字段之外,它们具有所有共同点。

SELECT count(*) as "units", (select count("EsnsVmas".*) from "EsnsVmas" where
      "EsnsVmas"."shipped" = false AND "EsnsVmas"."VmaId" = 2 AND "EsnsVmas"."approved" = 
       true) as "shippedUnits", "Vmas".*, "Vendors"."name" as "name", "EsnsVmas".id as    
       "OrderItemId", "PurchaseOrderItems"."price", "Grades"."name" as "vendorGrade", 
       "Items"."name" as "model", "Items".id as "ItemId", "Grades".id as "GradeId" 
FROM "Vmas" 
      JOIN "EsnsVmas" on ("EsnsVmas"."VmaId" = "Vmas".id) 
      JOIN "Esns" on ("EsnsVmas"."EsnId" = "Esns".id) 
      JOIN "PurchaseOrderItems"  on ("Esns"."PurchaseOrderItemId"  =  
            "PurchaseOrderItems".id) 
      JOIN "Items" on ("PurchaseOrderItems"."ItemId" = "Items".id) 
      JOIN "Grades" on ("PurchaseOrderItems"."GradeId" = "Grades".id) 
      JOIN "Vendors" on ("Vmas"."VendorId"  = "Vendors".id)
 WHERE "Vmas".id =2 AND "EsnsVmas"."approved" = true 
 GROUP BY "Vmas".id, "PurchaseOrderItems".id, "Grades".id, "Items".id, "Vendors".id, "EsnsVmas".id ;
4

1 回答 1

1

除了硬编码的 VmaId = "2" 之外,内部和外部查询之间似乎仍然没有关系。由于我没有数据库中的表,我无法测试以确保它有效 - 但这是我第一次尝试可能的修复:

SELECT count(*) as "units", (select count("EsnsVmas".*) from "EsnsVmas" e2 where
      e2."shipped" = false AND e2."VmaId" = "Vmas".id AND e2."approved" = 
       true AND "EsnsVmas".id = e2.id) as "shippedUnits", "Vmas".*, "Vendors"."name" as "name", "EsnsVmas".id as    
       "OrderItemId", "PurchaseOrderItems"."price", "Grades"."name" as "vendorGrade", 
       "Items"."name" as "model", "Items".id as "ItemId", "Grades".id as "GradeId" 
FROM "Vmas" 
      JOIN "EsnsVmas" on ("EsnsVmas"."VmaId" = "Vmas".id) 
      JOIN "Esns" on ("EsnsVmas"."EsnId" = "Esns".id) 
      JOIN "PurchaseOrderItems"  on ("Esns"."PurchaseOrderItemId"  =  
            "PurchaseOrderItems".id) 
      JOIN "Items" on ("PurchaseOrderItems"."ItemId" = "Items".id) 
      JOIN "Grades" on ("PurchaseOrderItems"."GradeId" = "Grades".id) 
      JOIN "Vendors" on ("Vmas"."VendorId"  = "Vendors".id)
 WHERE "Vmas".id =2 AND "EsnsVmas"."approved" = true 
 GROUP BY "Vmas".id, "PurchaseOrderItems".id, "Grades".id, "Items".id, "Vendors".id, "EsnsVmas".id ;

This changed two things. First was relating back with "EsnsVmas".id = e2.id at the end of the subselect (I aliased the EsnsVmas table in the subselect to e2). The other thing was changing e2."VmaId" = "Vmas".id (instead of hardcoding it to 2) which shouldn't affect the output but allows you to change the id in only one place.

于 2012-09-27T18:44:08.970 回答