开发者

What's the difference between table-based relations and column-based relations in RDBMS?

开发者 https://www.devze.com 2023-01-08 13:57 出处:网络
I have used column-based relations a lot in my projects like: CREATE TABLE `user` ( id INT AUTO_INCREMENT PRIMARY KEY,

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
);开发者_StackOverflow社区

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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消