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

时间:2018-11-08 17:23:15

标签: mysql record

我有表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 |
+---------------+------------+------+--------------+

表B中的表是一个临时表,每次购买产品时都会添加产品,然后将其删除。 发送后,我想更新表A中我在表B中具有product_id作为添加项的“ price_medium”列。

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

最终结果将在表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 |
+---------------+------------+------+--------------+

1 个答案:

答案 0 :(得分:1)

  • 您可以使用Inner Join在两个表之间进行id_product
  • 使用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