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



我正在为零售业务做项目,但对MySql数据有一些问题。我们有2个供应商的2张桌子。有些产品他们使用相同的名称不同的ID,但有些不是。只有供应商A才能提供某些产品。

供应商A产品ID产品名称A1产品1A2产品2供应商B产品ID产品名称B1产品1B2产品2.0B3产品3我想用我们自己的产品id创建一个新表,将其用作主要产品数据。产品表产品ID,A,B,产品名称P1 A1 B1产品1P2 A2空产品2P3空B2产品2.0P4空B3产品3

谢谢。

我建议使用三张表。第一个是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;

最新更新