0

我有一些怪物更新查询,如果不执行服务器端循环或任何操作,我无法完全适应一个查询。

我想使用其他两个表中的值更新一个主帐户表。主账户有 4 列,accountID、areaID、stockID 和 amount。前三列是主键。

我要更新详细信息的两张表几乎相同,一张是传入订单,一张是传出订单。它们都包含列 orderID、stockID 和 amount。主键是 orderID 和 stockID。

还有另一个表 orders,其中包含需要引用以更新主帐户表的订单的 areaID 和 accountID。到目前为止,我可以获得一个获取我想要的详细信息的选择函数,我只是不知道如何将它转移到更新语句。

SELECT a.*,o.orderID, SUM(io.amount) as in,SUM(oo.amount) as out
FROM account_stock AS a 
  INNER JOIN orders AS o ON o.accountID = a.accountID AND o.areaID = a.areaID 
  LEFT JOIN incoming_orders AS io ON io.stockID = a.stockID AND io.orderID = o.orderID 
  LEFT JOIN outgoing_orders AS oo ON oo.stockID = a.stockID AND oo.orderID = o.orderID
GROUP BY a.stockID,a.accountID,a.areaID

如果可以运行一个单独的更新查询,该查询将使用传入和传出库存的总和更新 account_stock 文件,我完全迷失了。

任何有关表结构更改等的建议都将受到欢迎,因为我知道我的 SQL 不是太传统。

4

1 回答 1

1

您可能应该在主表中创建两列,其中包含您在 select 语句中称为“in”和“out”的内容。然而,“In”是一个保留字,所以不要使用它。我没有在示例中重命名它,所以它对你更有意义。我已经重写了语句以使其成为更新而不是选择。

update
    account_stock a,
    INNER JOIN orders AS o 
        ON o.accountID = a.accountID 
        AND o.areaID = a.areaID
    LEFT JOIN incoming_orders AS io 
        ON io.stockID = a.stockID 
        AND io.orderID = o.orderID
    LEFT JOIN outgoing_orders AS oo 
        ON oo.stockID = a.stockID 
        AND oo.orderID = o.orderID
set
    a.in=sum(io.amount),
    a.oo=sum(oo.amount)

如评论中所述,这将导致 MySQL 翻转饼干,因为它不喜欢 set fieldname=aggFunc() 区域中的聚合函数。

以下代码应该可以工作:

update
    account_stock f
set
    a.amount=(
    SELECT 
        SUM(io.amount)-SUM(oo.amount)
    FROM 
        account_stock AS a
        INNER JOIN orders AS o 
            ON o.accountID = a.accountID 
            AND o.areaID = a.areaID
        LEFT JOIN incoming_orders AS io 
            ON io.stockID = a.stockID 
            AND io.orderID = o.orderID
        LEFT JOIN outgoing_orders AS oo 
            ON oo.stockID = a.stockID 
            AND oo.orderID = o.orderID
    where
        f.stockid=a.stockid
        and f.accountid=a.accountid
        and f.areaid=a.areaid
    )
于 2012-06-19T04:19:00.987 回答