首页 > 解决方案 > 如何使用另一个表中的新列更新现有表?

问题描述

我有两个数据库表。

**table 1:**

coupon_name || coupon_amount || coupon_id || coupon_status

**table 2:** 

coupon_id || coupon_name || store_name

我想在表 2 中添加 coupon_amount 列。如何在 mysql 中执行此操作?

标签: mysqlsqldatabase

解决方案


表 2 没有“coupon_amount”列,因此首先您必须将其添加到表中。下一步是将表 1 中的记录添加到目标表中。您可以使用此查询:

ALTER TABLE 'table2'
ADD COLUMN 'coupon_amount' INT (or the type of the field you have in table 1);

然后,您需要执行第二步,可以是这样的查询:

UPDATE 'table2'
INNER JOIN 'table1' ON 'table2'.'coupon_id' = 'table1'.'coupon_id'
SET 'table2'.'coupon_amount' = 'table1'.'coupon_amount';

推荐阅读