postgresql查询计数两组对象

时间:2012-09-27 18:05:25

标签: postgresql join

我在下面有这个加入查询。我有一个问题。 shippingUnits列出错了。它只计算总项目数。问题是我在计算两组具有共同点的对象,除了已发货的字段。

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 ;

1 个答案:

答案 0 :(得分: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 ;

这改变了两件事。首先是在子选择的末尾与"EsnsVmas".id = e2.id相关联(我将子选择中的EsnsVmas表别名为e2)。另一件事是改变e2."VmaId" = "Vmas".id(而不是硬编码为2),这不应该影响输出,但允许你只在一个地方更改id。