2015-05-11 38 views
0

我有一些表的设置和系统中的链接,像这样:SQL连接两个查询没有唯一的关系

产品

  • ActualID PK
  • 的ProductID
  • 项目ID

项目

  • 的ItemID PK
  • 数据ID

ItemsDataOne

  • 数据ID PK
  • 值(值I需要)

ItemsDataTwo

  • 数据ID PK
  • 价值(价值,我需要)

我在与以下选择那里有ProductIDs与自己的一个以上实例的问题:

select names.ProductID, names.Name, descriptions.Desc 
from 
    (select Products.ProductID, ItemsDataOne.Value as Name 
    from Products 
    inner join Items on Items.ItemI = Product.ItemID 
    inner join ItemsDataOne ON ItemsDataOne.DataID = Items.DataID) as names 
inner join 
    (select Products.ProductID, ItemsDataTwo.Value as Desc 
    from Products 
    inner join Items on Items.ItemI = Product.ItemID 
    inner join ItemsDataTwo ON ItemsDataTwo.DataID = Items.DataID) as descriptions 
on names.ProductID = descriptions.ProductID 

其中返回这样的副本:

实际结果

ProductID Name Description 
01   "One" "Description One" 
01   "Two" "Description One" 
01   "One" "Description Two" 
01   "Two" "Description Two" 

我想要什么

ProductID Name Description 
01   "One" "Description One" 
01   "Two" "Description Two" 
+0

你可以发布数据产生这样的结果? –

+0

'ItemsDataOne'和'ItemsDataTwo'是2张桌子? 'DataID'列不是与项目表相关的外键? – MacKentoch

+0

是的ItemsDataOne和ItemsDataTwoare是两个单独的表 – JamesTown

回答

3

可以更简单地完成,无需子查询:

select Products.ProductID, ItemsDataOne.Value, ItemsDataTwo.Value 
from Products 
inner join Items on Items.ItemID = Product.ItemID 
inner join ItemsDataOne ON ItemsDataOne.DataID = Items.DataID 
inner join ItemsDataTwo ON ItemsDataTwo.DataID = Items.DataID 

(你失踪ItemsDataOne和ItemsDataTwo之间的关系 - 他们需要有相同的DataID。)

+0

也可能添加'GROUP BY Products.ProductID,ItemsDataOne.Value,ItemsDataTwo.Value'。至少有一个提到它会很好 – Mackan

+0

@Mackan为什么分组?不同的会有同样的效果。 –

+0

@PavelGatnar是的,同样的事情(即相同的结果)。我只是经常默认由_too_组成);虽然 – Mackan