SQL多对多选择

时间:2010-08-15 08:01:37

标签: sql mysql many-to-many

category_product
---------------
id_category
id_product

product
---------------
id_product
id_manufacturer

manufacturer
---------------
id_manufacturer
name

我如何创建一个SQL查询,以便在id_category等于某事时从制造商中选择所有名称?

5 个答案:

答案 0 :(得分:34)

这是表格的直接内部联接:

SELECT m.name, cp.id_category
FROM manufacturer as m
INNER JOIN product as p
    ON m.id_manufacturer = p.id_manufacturer
INNER JOIN category_product as cp
    ON p.id_product = cp.id_product
WHERE cp.id_category = 'some value'

答案 1 :(得分:11)

没有连接的查询将如下所示:

SELECT m.name 
FROM manufacturer as m, product as p, category_product as cp 
WHERE cp.id_category = <your value>
      AND cp.id_product = p.id_product 
      AND p.id_manufacturer = m.id_manufacturer 

答案 2 :(得分:4)

Select M.name
From   manufacturer M
Where  M.id_manufacturer in ( Select P.id_manufacturer
                              From   product P
                              Where  P.id_product in ( Select C.id_product
                                                       From   category_product C
                                                       Where  C.id_category = ?))

答案 3 :(得分:0)

尝试类似

的内容
SELECT  m.*
FROM      category_product cp INNER JOIN
           product p ON cp.id_product = p.id_product INNER JOIN
           manufacturer m ON p.id_manufacturer = m.id_manufacturer
WHERE      cp.id_category = <your_value>

答案 4 :(得分:0)

SELECT m.name, cp.id_category
FROM manufacturer AS M INNER JOIN product AS P
    ON M.id_manufacturer = M.id_manufacturer
 INNER JOIN category_product AS CP
    ON P.id_product = CP.id_product 
WHERE cp.id_category = 'add value'