简体   繁体   中英

MySQL update table from another table values

I have two tables as finance_mpc_budget and finance_mpc_issues . They are joined with following condition-

finance_mpc_budget.mpc_budget_id = finance_mpc_issues.ref_no

So, I need to update finance_mpc_issues.ref_no using

finance_mpc_budget.mpc_budget_id where finance_mpc_budget.mpc_budget_id > 55

To do this I used the following query

UPDATE finance_mpc_issues 
JOIN (
      SELECT mpc_budget_id FROM finance_mpc_budget
      WHERE finance_mpc_budget.mpc_budget_id > 55 
      ORDER BY mpc_budget_id) a 
ON a.mpc_budget_id = finance_mpc_issues.ref_no 
SET finance_mpc_issues.ref_no = a.mpc_budget_id

But it generated the empty result set. What may be the wrong. Can anyone help me?

finance_mpc_budget table

+---------------+----------+--------+
| mpc_budget_id | category | amount |
+---------------+----------+--------+
|             56| A        |  22000 |
|             57| B        |  25000 |
|             58| C        |  45000 |
|             59| D        |  16000 |
+---------------+----------+--------+

finance_mpc_issues table

+-----------+--------+--------+
| issues_id | ref_no | amount |
+-----------+--------+--------+
|        10 |        |  22000 |
|        11 |        |  25000 |
|        12 |        |  45000 |
|        13 |        |  16000 |
+-----------+--------+--------+

Desired output

+-----------+--------+--------+
| issues_id | ref_no | amount |
+-----------+--------+--------+
|        10 |      56|  22000 |
|        11 |      57|  25000 |
|        12 |      58|  45000 |
|        13 |      59|  16000 |
+-----------+--------+--------+

You can try below -

update finance_mpc_issues 
join finance_mpc_budget a on a.mpc_budget_id = finance_mpc_issues.ref_no
set  finance_mpc_issues.ref_no=a.mpc_budget_id
where a.mpc_budget_id >55

You can not join using ref_no since it is null. Therefore your finance_mpc_issues table is not updated.

Based on your table and data , I assume amount column holds identical value. Therefore using amount column you can have your desired output.

Update finance_mpc_issues fi
set fi.ref_no = 
  (select fb.mpc_budget_id 
     from finance_mpc_budget fb 
     WHERE fb.amount = fi.amount
  );

fiddle link

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