Update table if conditions met. (update the value

2019-08-27 15:55发布

问题:

This question already has an answer here:

  • Match 2 sql columns if = then update a different column by 1 3 answers
  • How to do 3 table JOIN in UPDATE query? 5 answers

I have a table a in which i have fields 'date', 'time', cost and order_id

table b which has fields 'year' 'month' 'hour' 'cost' and order_id fields.

both tables are linked with "order_id" field. i want to update table a if year, month, hour and order_id is same in both tables and update the corresponding value from table b to table a field "cost"

I have used this statement, but query is not working? what is wrong in it? i need help

UPDATE item a, cost b
    SET a.cost = b.cost
    WHERE a.order_id = b.order_id
    AND YEAR(a.date) = b.YEAR
    AND month(a.date) = b.month
    AND hour(a.time) = b.hour

回答1:

UPDATE item a
JOIN cost b ON a.order_id = b.order_id
           AND YEAR(a.date) = b.YEAR
           AND month(a.date) = b.month
           AND hour(a.time) = b.hour
SET a.cost = b.cost