簡體   English   中英

MySQL:多次聯接到同一表,然后聯接到同一行中的另一個表

[英]MySQL: Multiple Joins to Same Table & then to Another Table in Same Row

我在LAMP環境中工作。

在MySQL中,我有3個表 ,並且要創建所需的報告 ,如下圖所示。

在此處輸入圖片說明

我如何實現這一目標。

由於表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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM