I am trying to learn about many to many relation in database tables using junction tables. Wikipedia doesn't have much info and explained in a confusing way, I was wondering if anyone knows where I can find great information on th net which can clearly and simply explain it to me?
It's really quite simple. You don't use many to many relations.
Joined: Jul 14, 2007
Campbell Ritchie wrote:It's really quite simple. You don't use many to many relations.
But I want to use many to many.
Why was it invented if we don't use it?
I haven't been able to find good explanations on this subject so I kinda sorta understand but will not be able to talk at length about it if called to do so. I still need you help friends
Consider orders and products.
Each order can have many products.
Each product can belong to many orders.
This is a classic example of many-to-many relationship.
In java we can implement this by storing a collection/array of references to the other objects:
- a product object has a collection/array of orders, and an order object stores references to products.
In the relational database it isn't as simple as in object oriented languages like java
- single row/field cannot store many references to other rows. In classic relational model there is no something like 'collection' field,
although some database implementations like Oracle 11 have feature called 'nested tables' - table nested in the single field of row in another table
(but this is not a 'classical relational model').
Obviously one can say "we can create 1000 fields in a row and store one reference in one field - but this is impractical and limited solution
(waste of disk space, number of fields in a row is limited in real databases, and what we will do if some day some order will have 1001 products ?).
Because in the relational model we cannot implement our products-orders relationship using only two tables (like in java - only two classes),
we have to add another 'junction' table (lets call it 'order items') that will store combinations of product-id / order-id.
In the end we have three tables:
Orders (order_id, .....)
Products( product_id, .....)
Order-items ( order_id, product_id, ....) - junction table
Joined: Oct 13, 2005
Explained far better than I could have
Joined: Jul 14, 2007
Thanks Ireneusz Kordal, your explanation is appreciated. Many thanks to all friends for reading.