2015-05-11 39 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