将多个连接表中的重叠行折叠为尽可能少的行

时间:2010-03-10 16:12:43

标签: sql query-optimization

Table_Design:

ID
"Alpha"
"Beta"

Table_Size:

Design_ID   Size
"Alpha"     S
"Alpha"     M
"Alpha"     L
"Beta"      S
"Beta"      L

Table_Color:

Design_Id   Color
"Alpha"     "Black"
"Alpha"     "Blue"
"Alpha"     "Red"
"Alpha"     "Green"
"Beta"      "Orange"

select D.ID, S.Size, C.Color from
Table_Design D
Left Outer Join
Table_Size S
ON D.ID = S.Design_Id
Left Outer Join
Table_Color C
ON D.ID = C.Design_Id
where
D.ID = 'Alpha'

收率:

D.ID    S.Size  C.Color
Alpha   S       Black
Alpha   S       Blue
Alpha   S       Red
Alpha   S       Green
Alpha   M       Black
Alpha   M       Blue
Alpha   M       Red
Alpha   M       Green
Alpha   L       Black
Alpha   L       Blue
Alpha   L       Red
Alpha   L       Green

无论如何都要写一个查询来代替它:

D.ID    S.Size  C.Color
Alpha   S       Black
Alpha   M       Blue
Alpha   L       Red
Alpha           Green

2 个答案:

答案 0 :(得分:1)

我假设您想要将第n行与第n行和颜色组合在一起。使用表格设计,您将无法显示,因为您无法可靠地识别表格的第n行。

我想说重新设计:制作一个单独的表来链接设计的大小和颜色(可以是NULL),你的查询将更容易。

答案 1 :(得分:0)

我不太喜欢以这种方式组合数据,但您可以执行以下操作:

Select Design_Id, 'Color' as Type, Color as Value from Table_Color where Design_Id = 'Alpha'
union all
Select Design_Id, 'Size' as Type, Size as Value from Table_Size where Design_Id = 'Alpha'

给出了

Design_Id Type  Value
========= ====  =====
Alpha     Color Black
Alpha     Color Blue
Alpha     Color Red
Alpha     Color Green
Alpha     Size  S
Alpha     Size  M
Alpha     Size  L