带有id列表的Mysql多连接查询

时间:2016-06-07 10:20:29

标签: mysql sql join

有3张桌子

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

如何在类别ID列表68,40,41,55,66中获取产品ID列表,并在一个SQL中使用制造商的ID列表210,788,233 ....和store_id = 1查询以避免使用php进行foreach循环并避免重复的产品ID?

2 个答案:

答案 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

答案 1 :(得分: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
相关问题