我正在尝试通过sequlized生成此类查询:
SELECT
"Customers"."id",
(SELECT SUM("Orders"."amount") FROM "Orders"
WHERE "Orders"."CustomerId" = "Customers"."id") AS "totalAmount",
"Customer"."lastName" AS "Customer.lastName",
"Customer"."firstName" AS "Customer.firstName"
FROM "Customers" AS "Customer";
我正在尝试避免使用GROUP BY
子句,因为我有很多字段可供选择,而且我不想将它们分组(我认为它效率不高,不是吗?)< / p>
我已经尝试了几种方法来实现续集,包括{include: ...}
和{attributes: [[...]]}
,但没有任何运气。
有什么想法吗?或者我应该使用一个大的GROUP BY
子句并让所有“常规”字段按类别分组?
答案 0 :(得分:3)
在Sequelize 4中,您可以使用attributes.include
语法http://docs.sequelizejs.com/manual/tutorial/querying.html
return Customer.findAll({
attributes: {
include: [
[sequelize.literal('(SELECT SUM("Orders"."amount") FROM "Orders"
WHERE "Orders"."CustomerId" = "Customer"."id")'), 'totalAmount']
]
}
});