SQL插入并根据其他表列将数据更新为列

发布于 2025-01-26 05:01:47 字数 1019 浏览 5 评论 0原文

我有两个桌子:
表产品表

| ProductID | ProductPrice  | ProductSupplier |
+-----------+---------------+-----------------+
| 1         |    25         | CompanyA        |
| 2         |    35         | CompanyB        |
| 3         |    12         | CompanyC        |  

供应商供应

商供应商名称
1Companya
2Companyb
3Companyc

如何根据表供应商的值却将新的列供应商插入表产品,但具有相应的column productsupplier值? 新的期望输出的示例: 餐桌产品

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

I have two tables:
table PRODUCTS

| ProductID | ProductPrice  | ProductSupplier |
+-----------+---------------+-----------------+
| 1         |    25         | CompanyA        |
| 2         |    35         | CompanyB        |
| 3         |    12         | CompanyC        |  

table SUPPLIERS

SupplierIDSupplierName
1CompanyA
2CompanyB
3CompanyC

How to insert new column SupplierID into table Products, based on values from table Suppliers but with corresponding values from column ProductSupplier?
example of new desired output:
Table PRODUCTS

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜味超标? 2025-02-02 05:01:47

使用更新加入:

UPDATE PRODUCTS p
INNER JOIN SUPPLIERS s
    ON s.SupplierName = p.ProductSupplier
SET p.SupplierID = s.SupplierID;

请注意,您正在朝着更正常化的方向移动,这是一件好事。假设您打算保留供应商表,则productsupplier products 表中的表现在是多余的,并且可以删除:

ALTER TABLE PRODUCTS DROP COLUMN ProductSupplier;

Use an update join:

UPDATE PRODUCTS p
INNER JOIN SUPPLIERS s
    ON s.SupplierName = p.ProductSupplier
SET p.SupplierID = s.SupplierID;

Note that you are moving in the direction of more normalization, which is a good thing. Assuming you are intending to keep the SUPPLIER table, then the ProductSupplier column in the PRODUCTS table is now redundant and can probably be dropped:

ALTER TABLE PRODUCTS DROP COLUMN ProductSupplier;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文