Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Update with Inner Join

I have 3 tables (simplified):

 tblOrder(OrderId INT)     tblVariety(VarietyId INT,Stock INT)     tblOrderItem(OrderId,VarietyId,Quantity INT) 

If I place an order, I drop the stock level using this:

UPDATE tblVariety   SET tblVariety.Stock = tblVariety.Stock - tblOrderItem.Quantity   FROM tblVariety   INNER JOIN tblOrderItem ON tblVariety.VarietyId = tblOrderItem.VarietyId   INNER JOIN tblOrder ON tblOrderItem.OrderId = tblOrder.OrderId   WHERE tblOrder.OrderId = 1 

All fine, until there are two rows in tblOrderItem with the same VarietyId for the same OrderId. In this case, only one of the rows is used for the stock update. It seems to be doing a GROUP BY VarietyId in there somehow.

Can anyone shed some light? Many thanks.

like image 658
Geoff Avatar asked Aug 12 '10 13:08

Geoff


People also ask

Can I use UPDATE with inner join?

SQL Server UPDATE JOIN syntax To query data from related tables, you often use the join clauses, either inner join or left join. In SQL Server, you can use these join clauses in the UPDATE statement to perform a cross-table update.

How do you UPDATE multiple columns in SQL using join?

Specify the column and value of the column that we want to update. We use the Set statement for specifying the values. Use SQL Join operator and specify the table name with join conditions. We can either use an Inner Join or Left Join in this predicate.

Can we use two tables in UPDATE query?

It is possible to join two or more tables in an UPDATE query.

Can we use UPDATE and SELECT together in SQL?

The subquery defines an internal query that can be used inside a SELECT, INSERT, UPDATE and DELETE statement. It is a straightforward method to update the existing table data from other tables. The above query uses a SELECT statement in the SET clause of the UPDATE statement.


1 Answers

My guess is that because you have shown us simplified schema, some info is missing that would determine why have the repeated VarietyID values for a given OrderID.

When you have multiple rows, SQL Server will arbritrarily pick one of them for the update.

If this is the case, you need to group first

UPDATE V SET    Stock = Stock - foo.SumQuantity FROM     tblVariety V     JOIN     (SELECT SUM(Quantity) AS SumQuantity, VarietyID      FROM tblOrderItem       JOIN tblOrder ON tblOrderItem.OrderId = tblOrder.OrderId        WHERE tblOrder.OrderId = 1      GROUP BY VarietyID     ) foo ON V.VarietyId = foo.VarietyId   

If not, then the OrderItems table PK is wrong because if allows duplicate OrderID/VarietyID combinations (The PK should be OrderID/VarietyID, or these should be constrained unique)

like image 52
gbn Avatar answered Sep 18 '22 02:09

gbn