简体   繁体   中英

How to update a column within a query in mysql

I want to update a column using aggregate function but I don't want to loop through each row. I'm coming from SQL Server where we do something like

With CTE as (select name, price, cost,  quantity price*quantity as total)
update CTE 
   set cost = total

With this I am able to update whole table without looping through every record. How can I accomplish the same task in mysql

Just do computation :

update sales 
    set cost = price * quantity
where . . . ;

However, the same would be work with SQL Server no need to use updateble CTE :

My suggestion is to not store cost column at all. Instead create a view:

CREATE VIEW sales_with_cost 
AS 
select name, price, cost,  quantity, price*quantity as total FROM sales

You can use sales_with_cost instead of sales directly and can ensure that your data is consistent without needing to do an update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM