2013-04-15 19 views
0

我有三個表的數據庫:的MySQL/PHP,獲得在一個所有的數據去

Products 
MaterialsProducts 
Materials 

表之間的關係是這樣的:

Materials 1-* MaterialsProducts *-1 Products 

很多時候我需要檢索200多種產品及其相關材料數據(來自Materials表)。

目前,它是這樣完成的:

SQL: select all relevant products 
PHP: iterate through the selected products, calling the database to select 
material data for each product(generating a database call for each product!)

有沒有辦法選擇的所有相關產品+他們的物質數據在同一時間?結果中每件產品只佔用一排。

所以解決方案不應該是"SELECT * FROM products p, materialsproducts mp, materials m WHERE p.id = mp.productid AND m.id = mp.materialid WHERE x"。 (這SELECT將使每一個產品佔用多行的結果。)

+1

您可以使用JOIN .. –

+0

你想每個產品一行,其中每個產品的成分是摺疊成一行? –

+0

這正是我想要的。每個產品一行,其中materialdata摺疊爲同一行中的1+個字段。 – Louisa

回答

0

可以使用left join得到你需要

文檔here

您的查詢有一個錯誤的所有數據

"SELECT * FROM `products` p LEFT JOIN `materialsproducts` mp on p.`id` = mp.`productid` LEFT JOIN `materials` m ON m.`id` = mp.`materialid` WHERE $whateveryouneed" 

記得不要限制你WHERE到只有1 ID否則你將需要更多的查詢。

UPDATED 的要求

products has a 1-* relationship with both materialsproducts and typesproducts. materialsproducts has a *-1 relationship with materials. typesproducts has a *-1 relationship with types.

所以,你可以這樣做一個left join查詢如上

SELECT * FROM `products` p 
LEFT JOIN `materialsproducts` mp 
ON p.`id` = mp.`productid` 
LEFT JOIN `materials` m 
ON mp.`mp_field_id_here` = m.`m_field_id_here` //here you need to change with actual field to compare 
LEFT JOIN `typesproducts` tp 
ON p.`id` = tp.`tp_field_id_here` //here you need to change with actual field to compare 
LEFT JOIN `types` t 
ON tp.`tp_field_id_here` = t.`t_field_id_here` //here you need to change with actual field to compare 

那麼你可以添加一個where statment到結果限制的東西,適合你

WHERE WHATEVER_YOU_NEED 

UPDATED AGAIN

到結果僅限制於某些申請只是改變*具體的東西作爲

"SELECT p.`Product_Name`, m.`Material_1`, m.`Material_2, m.`Material_3`, t.`Type_1`, t.`Type_2` FROM ..... 

注意我假設你檢索material 1, material 2, material 3material表至極就是爲什麼我作爲前綴m。無論哪種方式我用type 1 and type 2作爲前綴t,因爲我認爲它們是type表的文件夾,否則可以根據您的需要更改它們。

+0

如果我有兩個以上的表可以使用,那麼數據庫方案如下所示: 材料1- *材料產品* -1產品 類型1- *類型產品* -1產品 SQL將如何看待呢?我需要建立聯盟嗎? (即你的查詢材料UNION的查詢類型) 謝謝, 路易莎 – Louisa

+0

我看不到架構 – Fabio

+0

當時有點快上輸入按鈕... – Louisa

0

嘗試

SELECT p.*, mp.*,m.* 
FROM products p 
JOIN materials m ON p.id=m.prd_id 
JOIN materialsproducts mp ON m.mp_id=mp.id; 
+0

謝謝,但該查詢並未將每個產品的所有數據放在一行中。 – Louisa

+0

那麼你想要什麼? –

0

這不單純是有這樣的查詢壓縮材料數據到一個單獨的行,每個產品 - 所以我不認爲該計劃會爲你工作。

我推薦的是使用正常的JOIN查詢(非常類似於您在問題中放入的問題並拒絕),然後使用PHP代碼處理單個產品在結果集中有多行的情況因爲它與多種材料相關聯。

0

你可以使用GROUP_CONCAT同時通過產品分組到與同一產品材料結合到一個列表:

SELECT 
    p.ProductID, 
    p.ProductName, 
    GROUP_CONCAT(m.MaterialName) AS Materials 
FROM Products p 
INNER JOIN MaterialsProducts mp ON p.ProductID = mp.ProductID 
INNER JOIN Materials   m ON m.MaterialID = mp.MaterialID 
GROUP BY 
    p.ProductID, 
    p.ProductName 
; 
相關問題