映射表中的非规范化字段

时间:2011-11-15 16:50:37

标签: sql

我正在从一个未规范化的表(不是我的选择)中读取并尝试将其中的字段映射到另一个表。有没有办法在一次旅行中这样做?我正在使用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.FieldX1_ID的TableA.ID,TableB.FieldX_Value,TableA.FieldX2_ID的TableB.FieldX_Value等等......

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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