views:

64

answers:

3

Hi,

I have used column-based relations a lot in my projects like:

CREATE TABLE `user` (
id INT AUTO_INCREMENT PRIMARY KEY,
usergroup INT
);

CREATE TABLE `usergroup` (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);

however, at work it seems some people do it using table-based relations like this:

CREATE TABLE `user` (
id INT AUTO_INCREMENT PRIMARY KEY
);

CREATE TABLE `usergrouprelation` (
userid INT,
usergroupdid INT
);

CREATE TABLE `usergroup` (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);

and I am wondering here what are the pros and cons of both approach? And what is the official term for this?

+3  A: 

The relationships are different.

In your first example, a one to many relationship. One group can have many users. (a user can only be in one group)

In your second example, a many to many relationship. Many groups can have many users. (a user can be in more than one group and groups can have more than one user)

That's the difference between the two, it's common practice to use an intermediate table to break up a many to many relationship.

Chris Diver
I see, thank you!
rFactor
+1  A: 

There are no general pros or cons about that. I'd call your "column based relationship" a 1:n relation and your "table based relationship" a n:m relation.

1:n means every user can be related to zero or 1 user group and each user group can be related to many users.

n:m means, every user can be related to zero to many user groups and vice versa.

Greets Flo

Florian Reischl
+1  A: 

If you have many-to-many relationship you must go second way. But if you have one-to-many or many-to-one relationship you can choose any of two variants (but the second is more expandable).

See more: Database relationships

SKINDER