Launch Radio     |     Flip Skins

Modeling Many to Many Relationships
There are 3 basic types of relationships in the RDM (relational data model) framework.

  • One to One
  • One to Many
  • Many to Many
  • Most relationships in a relational database are of a one to many type. These are typically the type of relationships we think of in our day to day lives. For example, an employee can have one manager but a manager can have many employees. A child can have one biological father but a father can have many biological children. We handle these relationships by making the parent (manager/father) an attribute of the child (employee/offspring) since there can only be one for each entitiy. We almost do this without thinking somethimes since it's just the natural and obvious choice. One to one relationships are even more subconcious. An employee can have one phone line and a phone line can only belong to one employee. You might see a "phone number" field in the employee table and not even think about it twice but this is, in fact, a one to one relationship.

    What happens, however, when we have to deal with many to many relationships. A great example of a many to many relationship can be in a movie database. An actor can be in many movies and a movie can have many actors. In this scenario it would not be prudent to make the actor an attribute of the movie or make the move an attribute of the actor. This situation requires the creation of a 3rd table, specifically for the purpose of tracking the actor/movie association. This is especially usefull if the realtionship between actor and the movie has it's own unique attributes to track. For example how much the actor was paid or how many minutes of the film he/she appeared in.

    Let's take a look at what a 3 table structure accomodating all this data would look like.

    Notice that while the Actor_ID and Movie_ID are unique primary keys in their respective tables, they can be repeated infinitely in the MOVIES_ACTORS table. The only requirement is that their "combination" be unique. You can see many records for a given actor and many records for a given movie in this table. But only ONE record for the uniqe combination of an actor and a movie.

    Now let's say, for example, that we were interested in seeing a list of movies starring Vince Vaughn and what he got paid in each flick. Assuming further, that we don't know his Actor_ID right off hand, our query would look something like this:

    SELECT M.Title, MA.Payment
    FROM MOVIES M, MOVIES_ACTORS MA, ACTORS A
    WHERE M.Movie_ID = MA.Movie_ID
      AND MA.Actor_ID = A.Actor_ID
      AND A.First_Name = 'Vince'
      AND A.Last_Name = 'Vaughn'

    That's about it. Remember, proper data modeling is the most important aspect of any application and it can be the biggest favor you do for yourslef as a developer.


    © 2005 - 2012, MAXO Studio