[英]How to update a column within a query in mysql
我想使用聚合函數更新一列,但我不想遍歷每一行。 我來自SQL Server,我們在這里做類似的事情
With CTE as (select name, price, cost, quantity price*quantity as total)
update CTE
set cost = total
這樣我就可以更新整個表,而無需遍歷每條記錄。 我如何在mysql中完成相同的任務
只做計算:
update sales
set cost = price * quantity
where . . . ;
但是,無需使用updateble CTE
,對SQL Server
也可以使用:
我的建議是完全不存儲cost
列。 而是創建一個視圖:
CREATE VIEW sales_with_cost
AS
select name, price, cost, quantity, price*quantity as total FROM sales
您可以直接使用sales_with_cost
而不是sales
,並且可以確保數據一致而不需要進行更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.