简体   繁体   中英

Update a row based on another row

I'm working on my wordpress database, I would like to update my table wp_postmeta and set all _order_tax field to be calculated from _order_total with the formula :

_order_tax = 0.2 * _order_total

Here is a snapshot of my database (focusing two interesting rows) : 在此处输入图片说明

I want to do this update for each row where meta_key = _order_total but I don't know how to write that the new value should be based on the _order_total value from the same post_id

For example, I would like to write (symbolic language not sql):

Where post_id is 1834 then update meta_value of row containing _order_tax in meta_key column with meta_value*0.2 of row containing _order_total in meta_key and same post_id as the line I want to update.

I hope my question is clear.

Thanks for helping

You could use the UPDATE ... JOIN ... SET ... WHERE ... syntax as follows:

UPDATE wp_postmeta w1
INNER JOIN wp_postmeta w2 
    ON  w2.post_id = w1.post_id 
    AND w2.meta_key = '_order_total' 
SET w1.meta_value = w2.meta_value * 0.2
WHERE w1.meta_key = '_order_tax'

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