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?
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.
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.
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.
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'
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
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 = ?))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With