2011-11-15 37 views
0

我正在從未規範化(並非我的選擇)的表中讀取內容,並試圖將其中的字段映射到另一個表中。有沒有辦法在一次旅行中做到這一點?我正在使用Microsoft SQL。跨表格映射非規範化字段

TableA: 
ID 
FieldX1_ID (fixed set of fields that could have been better normalized) 
FieldX2_ID 
FieldX3_ID 

TableB: 
FieldX_ID (matches ID's in TableA's fields) 
FieldX_Value 

我想輸出行是: TableA.ID,TableB.FieldX_Value爲TableA.FieldX1_ID,TableB.FieldX_Value爲TableA.FieldX2_ID,等...

回答

0

你可以得到的結果有兩種方式。我不確定你的描述是哪一個。

若要將結果顯示在一個標準化的方式(你三排):

SELECT TableA.FieldX1_ID AS ID, TableB.FieldX_Value 
    FROM TableA JOIN TableB ON TableA.FieldX1_ID = TableB.FieldX_ID 
UNION ALL 
SELECT TableA.FieldX2_ID AS ID, TableB.FieldX_Value 
    FROM TableA JOIN TableB ON TableA.FieldX2_ID = TableB.FieldX_ID 
UNION ALL 
SELECT TableA.FieldX3_ID AS ID, TableB.FieldX_Value 
    FROM TableA JOIN TableB ON TableA.FieldX2_ID = Table3.FieldX_ID 

若要將結果顯示在非歸一化的方式(你會得到一個行):

SELECT TableA.FieldX1_ID AS ID1, TableB.FieldX_Value AS Value1, 
     TableA.FieldX2_ID AS ID2, TB2.FieldX_Value AS Value2, 
     TableA.FieldX3_ID AS ID3, TB3.FieldX_Value AS Value3, 
    FROM TableA JOIN TableB ON TableA.FieldX1_ID = TableB.FieldX_ID 
       JOIN TableB AS TB2 ON TableA.FieldX2_ID = TB2.FieldX_ID 
       JOIN TableB AS TB3 ON TableA.FieldX3_ID = TB3.FieldX_ID 
0

是的,你可以做這通過多次連接表A和B(對於表A中的每個列需要加入一次)。

例如:

SELECT 
    A.ID 
, FieldX1_Value = B1.FieldX_Value 
, FieldX2_Value = B2.FieldX_Value 
, FieldX3_Value = B3.FieldX_Value 
FROM A 
LEFT JOIN B B1 
    ON A.FieldX1_ID = B1.FieldX_ID 
LEFT JOIN B B2 
    ON A.FieldX2_ID = B2.FieldX_ID 
LEFT JOIN B B3 
    ON A.FieldX3_ID = B3.FieldX_ID