2012-04-23 47 views
1

給出的以下數據庫結構:可以在一個單獨的表格列上使用多個引用?

產品:

- id 
- model 
- manufacturerID 
- subcontractorID 

manufacturerID和subcontractorID被引用到同一個表,因爲有些廠商也在分包商:

製造商:

- id 
- name 

現在,如果我想選擇這兩列,我該怎麼做?

我想這樣的事情...

SELECT p.model, m.name AS Manufacturer, m.name AS Subcontractor 
FROM Product AS p 
LEFT JOIN Manufacturers AS m ON p.manufacturerID = m.id 
LEFT JOIN m ON p.subcontractorID = m.id 

...但我只能得到兩列值之一。

回答

1

關閉 - 你需要加入的廠商表兩次:

SELECT 
    p.model, manufacturer.name AS Manufacturer, 
    subcontractor.name AS Subcontractor 
FROM Product AS p LEFT JOIN 
    Manufacturers AS manufacturer 
    ON p.manufacturerID = manufacturer.id LEFT JOIN 
    Manufacturers AS subcontractor 
    ON p.subcontractorID = subcontractor.id 
+0

感謝您的快速反應! – macstens 2012-04-23 12:01:04

0

試試這個:

LEFT JOIN Manufacturers AS mman ON p.manufacturerID = mman.id 
LEFT JOIN Manufacturers AS msub ON p.subcontractorID = msub.id 
相關問題