mysql - 合并来自2个供应商相同产品但不同ID的两个mysql表

标签 mysql sql

我正在从事零售业务项目,但对 MySql 数据有一些问题。 我们有来自 2 个供应商的 2 张 table 。 有些产品使用相同的名称不同的 ID,但有些则不然。有些产品只有供应商 A 才能提供。

Supplier A
ProductID  productName
A1         Product 1
A2         Product 2


Supplier B
ProductID  productName
B1         Product 1
B2         Product 2.0
B3         Product 3

I want to create new table with our own Product id to use it as primary product data.

Products table
ProductID, A,    B,  productName 
P1          A1    B1   Product 1              
P2          A2    null Product 2
P3          null  B2   Product 2.0
P4          null  B3   Product 3

谢谢。

最佳答案

我建议三张 table 。第一个是 Products 表,其名称是从提供产品的供应商中选择的。第二个是 Suppliers 表,其中包含有关供应商的信息。第三个是 ProductSuppliers,每个供应商和产品一行。示例数据为:

create table Products (
    ProductId int not null auto_increment primary key,
    ProductName
);

create table Suppliers (
    SupplierId int not null auto_increment primary key,
    SupplierName
);

create table ProductSuppliers (
    ProductSuppliersId int not null auto_increment primary key,
    ProductId int not null references Products(ProductId),
    SupplierId int not null references Suppliers(SupplierId),
    SupplierProductCode varchar(255)
);

然后您可以从表格中填充这些内容:

insert into Products(ProductName)
    select ProductName
    from SupplierA
    union
    select ProductName
    from SupplierB;

insert into Suppliers(SupplierName)
    select 'A' union all select 'B';


insert into SupplierProducts(SupplierId, ProductId, SupplierProductCode)
    select s.SupplierId, p.ProductId, a.ProductCode
    from SupplierA a join
         Products p
         on a.ProductName = p.ProductName cross join
         (select SupplierId from Suppliers where SupplierName = 'A') s;

insert into SupplierProducts(SupplierId, ProductId, SupplierProductCode)
    select s.SupplierId, p.ProductId, b.ProductCode
    from SupplierB b join
         Products p
         on b.ProductName = p.ProductName cross join
         (select SupplierId from Suppliers where SupplierName = 'B') s;

关于mysql - 合并来自2个供应商相同产品但不同ID的两个mysql表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26204355/

相关文章:

MySQL,从两个表中选择时插入

php - 在 WordPress 中运行预定的 PHP 脚本以将数据保存在 MySQL 中

phpMyAdmin - auth_type 'config' 不工作

sql - if 和 else 语句都执行

mysql - 如何在现有的作业表设计之上设计一个关系数据库来跟踪不同类型的作业和作业状态?

sql - 在 dbplyr SQL 查询中的 string::str_detect 中使用带有正则表达式的变量

php - 如何让托管服务器及时运行特定的PHP代码?

mysql索引添加

sql - PostgreSQL 中 WITH .. AS .. 子句的替代方法

sql - 有用(困难)的 SQL 脚本库