将子查询序列化为字段

时间:2015-02-02 21:09:34

标签: sequelize.js

我正在尝试通过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子句并让所有“常规”字段按类别分组?

1 个答案:

答案 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']
        ]
    }
});