Sylar
Sylar

Reputation: 305

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 |
+---------------+------------+------+--------------+

Upvotes: 1

Views: 23

Answers (1)

Madhur Bhaiya
Madhur Bhaiya

Reputation: 28854

  • 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

Upvotes: 1

Related Questions