sql更新查询多个结果。 (没有内部联接和触发器)

时间:2016-09-12 10:54:16

标签: sql nested

UPDATE invoice 
SET totalAmount = ( SELECT SUM(price) AS 'total' 
                    FROM cart c , cartitem ci , item i 
                    WHERE c.cartId = ci.cartId AND ci.itemId = i.itemId 
                    AND c.cartId = 1
                )
WHERE cartId =1;

UPDATE invoice 
SET totalAmount = ( SELECT SUM(price) AS 'total' 
                    FROM cart c , cartitem ci , item i 
                    WHERE c.cartId = ci.cartId AND ci.itemId = i.itemId 
                    AND c.cartId = 2
                )
WHERE cartId =2;

请参考SQL代码。有没有任何解决方案可以立即更新所有记录,而不是按记录更新记录。顺便说一下,这是一个赋值,我不能使用内部联接或触发器。 谢谢。

5 个答案:

答案 0 :(得分:2)

使子查询与更新相关联(c.cartId = invoice.cartId),您将能够在单个语句中更新所需数量的发票。

UPDATE invoice 
SET totalAmount = ( SELECT SUM(price) AS 'total' 
                    FROM cart c , cartitem ci , item i 
                    WHERE c.cartId = ci.cartId AND ci.itemId = i.itemId 
                    AND c.cartId = invoice.cartId
                )
WHERE cartId in (1, 2);

答案 1 :(得分:2)

UPDATE invoice i
SET totalAmount = 
    ( SELECT SUM(price) AS 'total' 
        FROM cart c , cartitem ci , item i 
        WHERE c.cartId = ci.cartId AND ci.itemId = i.itemId 
        AND c.cartId = i.cartId
    )
WHERE cartId IN (1, 2);

如果您在cartId

中引用invoice作为字段

答案 2 :(得分:1)

试试这个它应该适合你:

UPDATE i SET i.totalAmount = t.total
FROM invoice i
INNER JOIN ( SELECT c.cartId, SUM(price) AS total
                FROM cart c , cartitem ci , item i 
                WHERE c.cartId = ci.cartId AND ci.itemId = i.itemId 
                AND c.cartId IN (1,2)
         GROUP BY c.cartId
) t ON t.cartId = i.cartId

答案 3 :(得分:1)

您可以为子查询创建标量函数,并将其用于更新totalAmount。 如

 --Select dbo.fnGetTotalCartAmount(1)
CREATE FUNCTION [dbo].[fnGetTotalCartAmount](@cartId int )
RETURNS numeric(18,2)
AS       
BEGIN
  declare @TotalAmount numeric(18,2)
                 SELECT @TotalAmount = SUM(price)
                    FROM cart c , cartitem ci , item i 
                    WHERE c.cartId = ci.cartId AND ci.itemId = i.itemId 
                    AND c.cartId = @cartId

 RETURN @TotalAmount;

END

并使用如下更新语句。

UPDATE invoice  SET totalAmount = dbo.fnGetTotalCartAmount(cartId)

答案 4 :(得分:0)

UPDATE invoice 
SET totalAmount = ( SELECT SUM(price) AS 'total' 
                    FROM cart c  join cartitem ci 
                    on c.cartId = ci.cartId join item i on  ci.itemId = i.itemId 
                    AND c.cartId  in (1,2)
                )
WHERE cartId  in (1,2)