2016-06-07 50 views
-2

有3個表mysql的多連接查詢與ID列表

products_to_stores

product_id | store_id 
___________________ 
50   | 1 
50   | 2 
66   | 1 
50   | 1 
111  | 3 
111  | 1 
51   | 1 
69   | 3 
69   | 2 

products_to_categories

product_id | category_id 
____________________ 
50   | 69 
50   | 68 
50   | 40 
51   | 66 
52   | 55 
69   | 41 
111  | 40 
111  | 70 

product_descriptions

product_id | manufacturer_id (parent category id) 
____________________ 
68   | 345 
69   | 233 
70   | 788 
50   | 788 
111  | 788 
51   | 210 
52   | 788 

如何獲得一個SQL查詢中內的類別列表的IDS產品68,40,41,55,66的IDS的列表...和製造商的IDS列表210788233 ....和STORE_ID = 1,以避免用PHP foreach循環並避免重複產品id?

+0

當你把...分類列表後/製造,你的意思是所有的類ID或只有你列出 –

+0

我的意思是上市 –

回答

2
SELECT DISTINCT p.product_id FROM products_to_stores p INNER JOIN products_to_categories c ON c.product_id = p.product_id INNER JOIN product_descriptions d ON d.product_id = p.product_id 
WHERE 
manufacturer_id IN (210,788) AND category_id IN (40,44) AND store_id = 1 
+0

的那些謝謝你的人。簡單 –

0
SELECT descriptions.product_id FROM product_descriptions AS descriptions 
    INNER JOIN products_to_categories AS category ON category.product_id = descriptions.product_id AND category.category_id IN (/* Your categories */) 
    INNER JOIN products_to_stores AS stores ON stores.product_id = descriptions.product_id AND stores.store_id = 1 
WHERE descriptions.manufacturer_id IN (/* .... */) 
GROUP BY descriptions.product_id