简体   繁体   中英

Update all the records of a field in a table whose value is only in another table

I have table A:

+---------------+------------+-------+-------------+
| name          | id_product | price | price_medium|
+---------------+------------+-------+-------------+
| phone         |         1  |   300 |         300 |
| mouse         |         2  |    50 |          75 |
| phone         |         1  |   250 |         300 |
| keyboard      |         3  |   100 |         100 |
| mouse         |         2  |   100 |          75 |
| phone         |         1  |   350 |         300 |
+---------------+------------+------+--------------+

In table B is a temporary table, products are added each time a purchase is made and then deleted. When it is sent, I want to update in table A the column "price_medium" that I have in table B whose product_id is the addition.

+---------------+------------+-------+-------------+
| name          | id_product | price | price_medium|
+---------------+------------+-------+-------------+
| phone         |         1  |   100 |         220 |
| mouse         |         2  |   125 |          92 |
| phone         |         1  |   100 |         220 |
+---------------+------------+------+--------------+

The final result would be in table A

+---------------+------------+-------+-------------+
| name          | id_product | price | price_medium|
+---------------+------------+-------+-------------+
| phone         |         1  |   300 |         220 |
| mouse         |         2  |    50 |          92 |
| phone         |         1  |   250 |         220 |
| keyboard      |         3  |   100 |         100 |
| mouse         |         2  |   100 |          92 |
| phone         |         1  |   350 |         220 |
+---------------+------------+------+--------------+
  • You can do an Inner Join between the two tables using id_product
  • Use Set to update price_medium in tableA (equal to price_medium in tableB)

Try:

UPDATE tableA AS tA
JOIN tableB AS tB ON tB.id_product = tA.id_product 
SET tA.price_medium = tB.price_medium

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