I have 3 tables that I want to combine, see below for details:
product.productID category.categoryID product.name product.price category.name(each one though, since a product can belong to more than one category)
What I want to do is get each product with the categories that relate to them in a single query. How would I got about this?
In this case the two tables are joined using the relationship table1.id = table2.id . It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.
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.
By definition, a many-to-many relationship is where more than one record in a table is related to more than one record in another table.
You need two joins:
SELECT product.productID, category.categoryID, product.name, product.price, category.name FROM product JOIN product_cat ON product.productID = product_cat.productID JOIN category ON category.categoryID = product_cat.categoryID
If a product could be in no categories and you still want to return it, change JOIN to LEFT JOIN in both places.
An alternative approach:
SELECT product.productID, product.name, product.price, GROUP_CONCAT(category.name) FROM product JOIN product_cat ON product.productID = product_cat.productID JOIN category ON category.categoryID = product_cat.categoryID GROUP BY product.productID
However it might be better just to use two queries instead of putting multiple values into a single cell.
You can use group_concat if using mySQL...
see this thread.
SQL to join one table to another table multiple times? (Mapping products to categories)
(possible duplicate)
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