1 回答
TA贡献1817条经验 获得超6个赞
和Aggregate
功能GroupBy
是朋友。聚合 | 耳鼻喉科
我修改了下面给出的代码并得到了一个非常优化的SQL查询,感谢 Ent 团队。
err := client.Basket.
Query().
Where(basketEntity.ID(ID)).
GroupBy(basketEntity.FieldID).
Aggregate(func(s *sql.Selector) string {
t := sql.Table(product.Table)
joinT := sql.Table(basketEntity.ProductsTable)
s.Join(joinT).
On(s.C(basketEntity.FieldID), joinT.C(basketEntity.ProductsPrimaryKey[0]))
s.Join(t).
On(t.C(product.FieldID), joinT.C(basketEntity.ProductsPrimaryKey[1]))
return sql.As(sql.Sum(t.C(product.FieldPrice)), "price")
}).
Aggregate(repository.Count()).
Scan(ctx, &report)
生成的SQL:
SELECT "baskets"."id", SUM("t2"."price") AS "price", COUNT(*)
FROM "baskets"
JOIN "basket_products" AS "t1" ON "baskets"."id" = "t1"."basket_id"
JOIN "products" AS "t2" ON "t2"."id" = "t1"."product_id"
WHERE "baskets"."id" = $1
GROUP BY "baskets"."id" args=[1]
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报