我真的需要为三种类型的用户使用单独的表吗?

时间:2019-03-08 09:42:41

标签: postgresql database-design

如果我有三种类型的用户。假设卖方,消费者和销售人员。我是否应该为单个表创建详细信息,例如名称,电子邮件密码和所有其他凭据等,并使用role_type表或每个表单独的表。考虑到DBMS的所有工程原理(如规范化等),这是大型项目的最佳方法。

还告诉我,如果我在表中有很多联接来执行某些操作,会影响应用程序的性能吗?

2 个答案:

答案 0 :(得分:2)

如果区别那些人的只有是角色,但所有细节都是相同的,那么我肯定会选择一张桌子。

但是,问题是,一个人可以扮演多个角色吗?如果不是这种情况,请在人员表中添加一个role_type列。根据这些角色的固定程度,可以使用查找表和外键,例如:

create table role_type
(
   id integer primary key,
   name varchar(20) not null unique
);

create table person
(
  id integer primary key, 
  .... other attributes ..., 
  role_id integer not null references role_type
);

但是,以我的经验来看,通常每个人只扮演一个角色是没有限制的,所以您将需要多对多关系船

create table role_type
(
   id integer primary key,
   name varchar(20) not null unique
);

create table person
(
  id integer primary key, 
  .... other attributes ..., 
);

create table person_role
(
  person_id integer not null references person, 
  role_id integer not null references role_type, 
  primary key (person_id, role_id)
);

答案 1 :(得分:1)

听起来这是在关系数据库中尝试对继承进行建模的一种情况。复杂的主题,已在herehere中进行了讨论。

听起来像您的“卖方,消费者,销售人员”一样将需要许多不同的属性和关系。卖方通常属于部门,有目标,与销售相关。消费者有购买记录,可能有信用额度,等等。

如果是这样,我建议“类表继承”可能是正确的解决方案。

可能看起来像这样。

create table user_account
(id int not null, 
username varchar not null, 
password varchar not null
....);

create table buyer
(id int not null, 
user_account_id int not null(fk), 
credit_limit float not null, 
....);

create table seller
(id int not null, 
user_account_id int not null(fk),
sales_target float,
....);

要回答您的其他问题-关系数据库已针对联接表进行了优化。数十年来的研究和开发已进入这一领域,一个设计良好的数据库(在要连接的列上带有索引)将不会由于连接而对性能产生明显影响。根据实际经验,具有数亿条记录和十个或更多联接的查询在现代硬件上运行非常快。