MySQL:多个连接到同一个表&然后到同一行中的另一个表

时间:2017-01-30 14:59:32

标签: mysql

我在LAMP环境中工作。

在MySQL中我有 3个表&我想创建所需报告,如下图所示。

enter image description here

我如何才能实现这一目标。

1 个答案:

答案 0 :(得分:2)

由于表ProductMaster在其FK_ProductTag_#字段中允许非ID整数,因此每个属性都需要一个特殊的连接(假设每个FK_ProductTag_#都有一个" 0"值。这是请求的查询:

select a.ProductName as 'Product Name', 
a.Attr1 as 'Atrribute-1', 
b.Attr2 as 'Attribute-2', 
c.Attr3 as 'Atrribute-3' from
  (select m.ProductName as 'ProductName',
  concat_ws(': ', tagtype.Description, tag1.Description) as 'Attr1'
  from ProductMaster m
  left join ProductTag tag1 on m.FK_ProductTag_1 = tag1.ID
  left join ProductTagType tagtype on tag1.FK_ProductTagType = tagtype.ID) as a
join
  (select m.ProductName as 'ProductName',
  concat_ws(': ', tagtype.Description, tag2.Description) as 'Attr2'
  from ProductMaster m
  left join ProductTag tag2 on m.FK_ProductTag_2 = tag2.ID
  left join ProductTagType tagtype on tag2.FK_ProductTagType = tagtype.ID) as b
on a.ProductName = b.ProductName
join
  (select m.ProductName as 'ProductName',
  concat_ws(': ', tagtype.Description, tag3.Description) as 'Attr3'
  from ProductMaster m
  left join ProductTag tag3 on m.FK_ProductTag_3 = tag3.ID
  left join ProductTagType tagtype on tag3.FK_ProductTagType = tagtype.ID) as c
on a.ProductName = c.ProductName
order by a.ProductName asc

有关演示,请参阅此SQLFiddle

SQLFiddle在测试期间正在执行,因此将上述查询和下表模式复制到SQLTest以进行演示:

create table ProductTagType (ID int not null auto_increment, Description varchar(20), primary key (ID));
create table ProductTag (ID int not null auto_increment, Description varchar(20), FK_ProductTagType int(1), primary key (ID));
create table ProductMaster (ID int not null auto_increment, ProductName varchar(20), FK_ProductTag_1 int(1), FK_ProductTag_2 int(1), FK_ProductTag_3 int(1), primary key (ID));
insert into ProductTagType (Description)
values ('Imported'), ('Local'), ('HomeMade');
insert into ProductTag (Description, FK_ProductTagType)
values ('Wood', 2), ('Plastic', 2), ('Steel', 1), ('Aluminum', 3);
insert into ProductMaster (ProductName, FK_ProductTag_1, FK_ProductTag_2, FK_ProductTag_3)
values ('Chair', 1, 2, 3), ('Table', 0, 3, 4);