2016-09-12 58 views
-2

目前我正在尋找解決方案。英語不是我的母語,所以我添加了兩張圖片來澄清一點。我對SQL的瞭解很基本。SQL疑難陳述

Table Database

一種椅子(終產物)含有幾個組件。
每個組件都包含一個項目編號,每個備用集合包含多個項目編號。
在數據庫中,備用組與最終產品位於同一個表中。
椅子和零件分爲不同的組別。

是否有可能創建一個這樣的表?如果可能如何?

在此先感謝!

+0

學校分配?你有什麼嘗試? – jarlh

+0

使用一張桌子可能不是最好的解決方法。你肯定會需要多個相互關聯的表格。 – Fleuv

+0

@jarlh,這是一個實習。我可以用兩張不同的表格,但不能將兩者結合起來。 – Jur

回答

1

這將是我的做法:

Table: Products -- a table of products 
ProductID ProductName DateAdded 
1   Chair X  01/01/2016 
2   Chair Y  05/05/2016 
3   Spare Set A 06/06/2016 
... 

Table: Components -- a table of components 
ComponentID ComponentName ItemNumber DateAdded 
1   Backrest  X01   01/01/2016 
2   Headrest  X02   01/01/2016 
... 

Table: ProductComponent -- a lookup/mapping table to link Product and Component 
PCID ComponentID ProductID DateAdded 
1  1   1   01/01/2016 
2  2   1   01/01/2016 
... 

DateAdded是產品或組件首先輸入到數據庫的日期。它用於審計目的。

0

下面的查詢使用標準SQL來生成這樣一個數據透視表。
而且還應該在MySQL中工作。

它基於JohnHC答案的表格佈局。
(會做這樣的事情呢。使用映射表是一種常見的非規範化方法。)

select c.ComponentName 
,max(case when p.ProductName = 'Chair X' then 'x' else ' ' end) as Chair_X 
,max(case when p.ProductName = 'Chair Y' then 'x' else ' ' end) as Chair_Y 
,max(case when p.ProductName = 'Chair Z' then 'x' else ' ' end) as Chair_Z 
,max(case when p.ProductName = 'Spare Set A' then 'x' else ' ' end) as Spare_set_A 
,max(case when p.ProductName = 'Spare Set B' then 'x' else ' ' end) as Spare_set_B 
,max(case when p.ProductName = 'Spare Set C' then 'x' else ' ' end) as Spare_set_C 
from ProductComponent pc 
inner join Products p on (pc.ProductID = p.ProductID) 
left join Components c on (pc.ComponentID = c.ComponentID) 
where (p.ProductName like 'Chair %' or p.ProductName like 'Spare Set %') 
group by c.ComponentName 
order by c.ComponentName;