SOLVED
I'm stuck with something and I'm not even sure if it's possible what I'm trying to do.
Basically I want to update (or better yet, right away with the insert) a specific field with a multiplication from the current table AND a value from another table.
This is the query so far :
UPDATE Orders
SET Total = (SELECT p.Price * o.Quantity
FROM Products p, Orders o
WHERE p.ProductID = o.ProductID
AND p.ProductID = 110)
WHERE o.OrderID = 112;
The strange thing is, when I run the SELECT part exclusively, it returns a clean integer.
When I delete the 'subquery' and insert this number in it's place, the UPDATE query works fine, however when I try to do it like shown above I get an error
'Operation must use an updateable query'
Has anyone ever seen and solved this problem? Any help will be very much appreciated, thanks in advance
EDIT
Thanks for the help guys, I had to do some tweaking, but now it works perfectly. I've used the query below : (Just to be clear, it's an .mdb Access database)
UPDATE Orders
INNER JOIN Products ON Products.ProductID = Orders.ProductID
SET Orders.Total = Orders.Price * Orders.Quantity
WHERE OrderID = 112;
答案 0 :(得分:1)
I think you want the subquery correlated with the outer query:
UPDATE Orders
SET Total = (SELECT p.Price * orders.Quantity
FROM Products as p
WHERE p.ProductID = 110
)
WHERE orders.OrderID = 112;
Your version takes quantity
from the orders for product 110 instead of 112.
EDIT:
You can also express this as a join:
UPDATE o
SET Total = p.Price * orders.Quantity
FROM Orders o,
(SELECT *
FROM Products as p
WHERE p.ProductID = 110
) as p
WHERE orders.OrderID = 112;
答案 1 :(得分:0)
您可以直接加入所述表并相应地执行更新,如
UPDATE Orders
INNER JOIN Products ON Products.ProductID = Orders.ProductID
AND Products.ProductID = 110
AND Orders.OrderID = 112
SET Total = Products.Price * Orders.Quantity;
答案 2 :(得分:0)
我认为这将是稍微好一点的选择。它与Gordon的查询类似,但在Products和Orders表之间使用显式JOIN,而不是表之间的隐式交叉连接。
UPDATE o
SET Total = p.Price * o.Quantity
FROM Products p
INNER JOIN Orders o
ON p.ProductID = o.ProductID
WHERE o.OrderID = 112
AND p.ProductID = 110
虽然结果会相同,但建议使用这种写作查询方式,因为我相信Gordon也会提出建议。