我正在从事零售业务项目,但对 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/