SQL 根据其他 Table 列向列中插入和更新数据
SQL insert and update data into column based on other Table column
我有两个 table:
table 产品
| ProductID | ProductPrice | ProductSupplier |
+-----------+---------------+-----------------+
| 1 | 25 | CompanyA |
| 2 | 35 | CompanyB |
| 3 | 12 | CompanyC |
table 供应商
SupplierID
SupplierName
1
CompanyA
2
CompanyB
3
CompanyC
如何根据 table 供应商的值但使用 ProductSupplier 列的相应值将新列 SupplierID 插入 table 产品?
新的期望输出示例:
Table 产品
| ProductID | ProductPrice | ProductSupplier | SupplierID |
+-----------+---------------+-----------------+------------+
| 1 | 25 | CompanyA | ID value from table Suppliers |
| 2 | 35 | CompanyB | ID value from table Suppliers |
| 3 | 12 | CompanyC | ID value from table Suppliers |
使用更新连接:
UPDATE PRODUCTS p
INNER JOIN SUPPLIERS s
ON s.SupplierName = p.ProductSupplier
SET p.SupplierID = s.SupplierID;
请注意,您正朝着更加规范化的方向前进,这是一件好事。假设您打算保留 SUPPLIER
table,那么 PRODUCTS
table 中的 ProductSupplier
列现在是多余的,可能会被删除:
ALTER TABLE PRODUCTS DROP COLUMN ProductSupplier;
我有两个 table:
table 产品
| ProductID | ProductPrice | ProductSupplier |
+-----------+---------------+-----------------+
| 1 | 25 | CompanyA |
| 2 | 35 | CompanyB |
| 3 | 12 | CompanyC |
table 供应商
SupplierID | SupplierName |
---|---|
1 | CompanyA |
2 | CompanyB |
3 | CompanyC |
如何根据 table 供应商的值但使用 ProductSupplier 列的相应值将新列 SupplierID 插入 table 产品? 新的期望输出示例: Table 产品
| ProductID | ProductPrice | ProductSupplier | SupplierID |
+-----------+---------------+-----------------+------------+
| 1 | 25 | CompanyA | ID value from table Suppliers |
| 2 | 35 | CompanyB | ID value from table Suppliers |
| 3 | 12 | CompanyC | ID value from table Suppliers |
使用更新连接:
UPDATE PRODUCTS p
INNER JOIN SUPPLIERS s
ON s.SupplierName = p.ProductSupplier
SET p.SupplierID = s.SupplierID;
请注意,您正朝着更加规范化的方向前进,这是一件好事。假设您打算保留 SUPPLIER
table,那么 PRODUCTS
table 中的 ProductSupplier
列现在是多余的,可能会被删除:
ALTER TABLE PRODUCTS DROP COLUMN ProductSupplier;