Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL join many to many single row

Tags:

I have 3 tables that I want to combine, see below for details:

product

  • productID
  • name
  • price

prod_cat

  • productID
  • categoryID

category

  • categoryID
  • name

joined

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?

like image 426
Nathan Stanford II Avatar asked Mar 01 '11 18:03

Nathan Stanford II


People also ask

How do I join many-to-many tables in SQL?

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.

How do I create a many-to-many relationship in MySQL?

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.

What kind of join is many-to-many?

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.


2 Answers

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.

like image 76
Mark Byers Avatar answered Sep 30 '22 18:09

Mark Byers


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)

like image 40
Brandon Frohbieter Avatar answered Sep 30 '22 18:09

Brandon Frohbieter