更新一个table中一个字段的所有记录,其值仅在另一个table中

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

我有table答:

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

在table中,B 是临时的table,每次购买时都会添加产品,然后删除。 发送后,我想在 table A 中更新 table B 中的列 "price_medium",其 product_id 是加法。

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

最后的结果会是 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 |
+---------------+------------+------+--------------+
  • 您可以使用 id_product
  • 在两个表之间执行 Inner Join
  • 使用Set更新表A中的price_medium(等于表B中的price_medium

尝试:

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