将SQL查询更改为在JOIN

时间:2018-10-11 11:41:57

标签: sql postgresql greatest-n-per-group

我有以下sql查询

SELECT "Item"."id",
       "Item"."name",
       "Item"."active",
       "Item"."vendible",
       "Item"."purchasable",
       "Item"."type",
       "Item"."listNetPrice",
       "vendors"."id" AS "vendors.id",
       "vendors->PartnerItems"."createdAt" AS "vendors.PartnerItems.createdAt",
       "vendors->PartnerItems"."updatedAt" AS "vendors.PartnerItems.updatedAt",
       "vendors->PartnerItems"."ItemId" AS "vendors.PartnerItems.ItemId",
       "vendors->PartnerItems"."PartnerId" AS "vendors.PartnerItems.PartnerId",
       "VatKey"."id" AS "VatKey.id",
       "VatKey"."key" AS "VatKey.key"
FROM "overseer"."Item" AS "Item"
  INNER JOIN ("overseer"."PartnerItems" AS "vendors->PartnerItems"
  INNER JOIN "overseer"."Partner" AS "vendors" ON "vendors"."id" = "vendors->PartnerItems"."PartnerId")
          ON "Item"."id" = "vendors->PartnerItems"."ItemId"
         AND ("vendors"."id" = 1
          OR "vendors"."id" = 2)
  LEFT OUTER JOIN "overseer"."VatKey" AS "VatKey" ON "Item"."VatKeyId" = "VatKey"."id"
WHERE ("Item"."name" ilike '%%' OR "Item"."tariffNo" ilike '%%')
ORDER BY "Item"."id" ASC LIMIT 5 OFFSET 0

给出以下结果

query result image

“我的项目”可以有许多合作伙伴(具有多对多关联),如果它们仅与一个我没有问题,则关联,但是如果单个项目有更多的合作伙伴,则会出现上述问题。同一项目被多次选择,我只希望它们显示一次,与拥有多少伙伴无关。

0 个答案:

没有答案