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

ngynwnxp  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(398)

我有一张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 |
+---------------+------------+------+--------------+

在表b中是一个临时表,每次购买时都会添加产品,然后删除。发送时,我想在表a中更新表b中的“price\u medium”列,该列的产品id是加法。

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

r6vfmomb1#

你可以做一个 Inner Join 在两张table之间使用 id_product 使用 Set 更新 price_medium 表A中(等于 price_medium 在表b中)
尝试:

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

相关问题