【发布时间】:2016-12-01 18:51:40
【问题描述】:
我想这样做:
select sum("quantity") as "sum"
from "orderArticles"
inner join "orders"
on "orderArticles"."orderId"="orders"."id"
and "orderArticles"."discountTagId" = 2
and "orders"."paid" is not null;
结果在我的数据库中:
sum
-----
151
(1 row)
我该怎么做?
我的 Sequelize 解决方案:
模型定义:
const order = Conn.define('orders', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
// ...
paid: {
type: Sequelize.DATE,
defaultValue: null
},
// ...
},
// ...
})
const orderArticle = Conn.define('orderArticles',
{
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
// ...
quantity: {
type: Sequelize.INTEGER,
defaultValue: 1
}
},
{
scopes: {
paidOrders: {
include: [
{ model: order, where: { paid: {$ne: null}} }
]
}
},
// ...
})
协会:
orderArticle.belongsTo(order)
order.hasMany(orderArticle, {onDelete: 'cascade', hooks: true})
经过数小时的研究,我想出了这个:
db.models.orderArticles
.scope('paidOrders') // select only orders with paid: {$ne: null}
.sum('quantity', { // sum up all resulting quantities
attributes: ['quantity'], // select only the orderArticles.quantity col
where: {discountTagId: 2}, // where orderArticles.discountTagId = 2
group: ['"order"."id"', '"orderArticles"."quantity"'] // don't know why, but Sequelize told me to
})
.then(sum => sum) // return the sum
导致这条sql:
SELECT "orderArticles"."quantity", sum("quantity") AS "sum", "order"."id" AS "order.id", "order"."taxRate" AS "order.taxRate", "order"."shippingCosts" AS "order.shippingCosts", "order"."discount" AS "order.discount", "order"."paid" AS "order.paid", "order"."dispatched" AS "order.dispatched", "order"."payday" AS "order.payday", "order"."billNr" AS "order.billNr", "order"."createdAt" AS "order.createdAt", "order"."updatedAt" AS "order.updatedAt", "order"."orderCustomerId" AS "order.orderCustomerId", "order"."billCustomerId" AS "order.billCustomerId" FROM "orderArticles" AS "orderArticles" INNER 在 "orderArticles"."orderId" = "order"."id" 上加入 "orders" 作为 "order" AND "order"."paid" 不是 NULL WHERE "orderArticles"."discountTagId" = '4' GROUP BY "order"."id", "orderArticles"."quantity";
在同一个数据库上有这个结果:0 rows
如果你知道我做错了什么,请告诉我! 谢谢你:)
【问题讨论】:
标签: sql join associations subset sequelize.js