NodeJS 如何计算续集中的totalPrice?

nr7wwzry  于 4个月前  发布在  Node.js
关注(0)|答案(2)|浏览(40)

我有四个表Users,Orders,OrderProducts(joın table),Products,
我想计算订单表中的totalprice cloumn,OrderProducts有数量和productId,product有价格列,我想计算总价列订单表,
是否需要在OrderProducts表中为每个项目添加价格列(价格 * 数量)?

u4vypkhs

u4vypkhs1#

您不一定需要在OrderProducts表中添加价格列,可以通过在表之间创建Sequelize关联并使用Sequelize的聚合函数来实现。

Orders.hasMany(OrderProducts);
OrderProducts.belongsTo(Products);

字符串
现在,您可以在查询过程中根据相关数据动态计算总价,方法是使用Sequelize的 *SUM * 函数将OrderProducts的数量乘以Products的价格,从而得出每个订单的总价:

const ordersWithTotalPrice = await Orders.findAll({
attributes: [
    'id',
    [sequelize.fn('SUM', sequelize.literal('`OrderProducts`.`quantity` * `Products`.`price`')), 'totalPrice']
],
include: [
    {
        model: OrderProducts,
        attributes: [],
        include: [
            {
                model: Products,
                attributes: []
            }
        ]
    }
],
group: ['Orders.id']
});

console.log(ordersWithTotalPrice);


它相当于执行以下SQL查询:

SELECT 
Orders.id,
SUM(OrderProducts.quantity * Products.price) AS totalPrice
FROM 
Orders
JOIN 
OrderProducts ON Orders.id = OrderProducts.OrderId
JOIN 
Products ON OrderProducts.ProductId = Products.id
GROUP BY 
Orders.id;


这种方法确保Orders表中的totalPrice列保持最新,而不需要冗余数据存储。

omtl5h9j

omtl5h9j2#

您不一定需要向OrderProducts表中添加price列。相反,您可以在需要时通过在查询中连接必要的表来计算总价。以下是一种通用方法:
1.数据库架构:

  • 用户(用户ID、用户名...)
  • 订单(OrderId,UserId,TotalPrice,.)
  • OrderProducts(Id,OrderId,ProductId,Quantity,...)
  • 产品(ProductId,Price,.)

1.**查询计算总价:**通过连接Orders、OrderProducts和Products表,可以使用查询计算总价:

SELECT
    O.OrderId,
    O.UserId,
    SUM(OP.Quantity * P.Price) AS TotalPrice
FROM
    Orders O
    JOIN OrderProducts OP ON O.OrderId = OP.OrderId
    JOIN Products P ON OP.ProductId = P.ProductId
GROUP BY
    O.OrderId, O.UserId;

字符串
在此查询中,SUM(OP.Quantity * P.Price)通过将OrderProducts中的数量乘以Products表中相应的产品价格来计算每个订单的总价。
通过这种方式组织数据,可以避免冗余,并确保始终根据当前产品价格计算总价。如果产品价格发生变化,历史订单的总价仍将反映正确的值。
1.**更新订单表中的总价:**如果您想将总价存储在Orders表中以便快速检索,可以使用计算值更新:

UPDATE Orders O
SET TotalPrice = (
    SELECT SUM(OP.Quantity * P.Price)
    FROM OrderProducts OP
        JOIN Products P ON OP.ProductId = P.ProductId
    WHERE O.OrderId = OP.OrderId
);


此查询根据计算的总和为每个订单更新Orders表中的TotalPrice列。
请记住根据实际数据库模式调整列名和表名。在Orders表中添加TotalPrice列是一种常见的做法,可以在经常需要检索总价而无需每次重新计算时提高查询性能。

相关问题