0

The following is the MS Sql server Update statement

    Update 
        HC_TranDetails
SET
        InsPayments = (SELECT IsNull(SUM(ISNULL(CreditAmount,0)),0) From HC_TranDetails TDS
                        Where TDS.TransactionType = 2 
                        AND TDS.ClaimNo = TD.ClaimNo 
                        AND TDS.LineItemNo = TD.LineItemNo 
                        AND IsNull(TDS.InsPlanRowID,'') <> ''
                        AND TDS.ReverseEntry <> 1 ),

        Adjustments = (SELECT IsNull(SUM(ISNULL(CreditAmount,0)),0) From HC_TranDetails TDS
                        Where TDS.TransactionType = 8
                        AND TDS.ClaimNo = TD.ClaimNo 
                        AND TDS.LineItemNo = TD.LineItemNo 
                        AND IsNull(TDS.InsPlanRowID,'') <> ''
                        AND TDS.ReverseEntry <> 1 ),


FROM
        HC_TranDetails TD

Now i am trying the same kind of statement in mysql as follows

    UPDATE claimdetails SET balanceAmount =  (SELECT IFNULL(SUM(IFNULL(debitamount,0)) -  SUM(IFNULL(creditamount,0)),0) 
                      FROM claimdetail CD WHERE CD.claimID = CDS.claimID)

FROM ClaimDetail CDS

But it is showing as syntax Error near 'From ClaimDetail CDS' at line 4

4

2 回答 2

1

您可以使用子查询连接要更新的表,该子查询计算claimid另一个表上每个表的余额。

通过使用LEFT JOIN,它将更新表上的所有记录claimdetails。的值0将更新为claimid子查询中不存在的任何值。

UPDATE  claimdetails a
        LEFT JOIN 
        (
            SELECT  claimID, 
                    SUM(IFNULL(debitamount, 0)) - SUM(IFNULL(creditamount,0)) bal
            FROM    claimdetail
            GROUP   BY claimID
        ) b ON a.claimID = b.claimID
SET     a.balanceAmount = IFNULL(b.bal, 0)
于 2013-11-06T15:55:05.900 回答
1

MySQL 对同一张表上的更新很敏感。简单的解决方法是包含额外级别的子查询。但是,正确的解决方法是使用连接

UPDATE claimdetails join
       (select claimid, IFNULL(SUM(IFNULL(debitamount,0)) -  SUM(IFNULL(creditamount,0)),0) as val
        from ClaimDetails
        group by claimid
       ) agg
       on claimdetails.claimid = agg.claimid
    SET balanceAmount = agg.val;
于 2013-11-06T15:55:52.420 回答