Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL many to many select

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

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

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

How would I create an SQL query so that it selects all the names from manufacturer when id_category is equal to something?

like image 430
Ken Avatar asked Aug 15 '10 08:08

Ken


People also ask

How do I do a many-to-many relationship in SQL?

When you need to establish a many-to-many relationship between two or more tables, the simplest way is to use a Junction Table. A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table.

How do you make a many-to-many relationship table?

Connect the three tables to create the many-to-many relationship. To complete the many-to-many relationship, create a one-to-many relationship between the primary key field in each table and the matching field in the intermediate table. For details on how to do this, see Get started with table relationships.

What are relationships in SQL?

Relationships are the established associations between two or more tables. Relationships are based on common fields from more than one table, often involving primary and foreign keys. A primary key is the field (or fields) that is used to uniquely identify each record in a table.


3 Answers

It's a straightforward inner join of the tables:

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' 
like image 65
chryss Avatar answered Sep 21 '22 06:09

chryss


Query without joins will look like following :

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 
like image 22
YoK Avatar answered Sep 20 '22 06:09

YoK


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 = ?))
like image 27
CooL i3oY Avatar answered Sep 22 '22 06:09

CooL i3oY