具有类型和子类型的数据库设计

时间:2015-08-11 00:21:09

标签: mysql database-design subtype

我正在尝试设计一个具有超类型/子类型的数据库。我有以下用户:
- 基本用户
- 商业用户
- 管理员(超级用户)。

所有三个用户共享一个公共表(用户),其中存储了名称,电子邮件,密码等字段。但是,业务用户有一个单独的表(业务),其中存储了business_name,business_license,business_email等业务字段。我的问题是我的业务用户自己被分为5个或更多类别 我的业务用户分为这样:

  1. 画家
  2. 车辆细部
  3. 很多服务员
  4. 服务技术人员:
    1. 发动机技师
    2. 传动技术员
    3. 计算机技术人员
    4. 电气技师
  5. 销售代表
    1. 物理位置销售代表
    2. 互联网销售代表
    3. 销售经理
  6. 有一点需要注意的是,我希望将所有这些业务用户存储到某个表中,以便轻松添加和删除位置,而不会在应用程序级别上乱七八糟。

    我目前设计的这个数据库,但我并不满意。有更好的方法吗?

    enter image description here

1 个答案:

答案 0 :(得分:0)

你的设计很不错。我喜欢。在其中放入一些数据并编写一些查询。如果您愿意,可以将它标准化一点。这里是您可以使用http://sqlfiddle.com/#!9/b0711/3播放的SQLFiddle,以下是语句。

用户和类型

create table usertypes (id int, typename varchar(100));
insert into usertypes values (1,'Basic'), (2, 'Business'), (3, 'Super');

create table users (
  id int, 
  email varchar(100), usertype int, fullname varchar(100)
);
insert into users values 
(1, 'a@b.com', 1, 'Tom Basic'),
(2, 'b@c.com', 2, 'Bill Business'),
(3, 'c@d.com', 3, 'Charlie Super');

-- USERS will have SUBTYPES in this many to many table. This will allow
-- a user to be a part of multiple subtypes if you please. You can control
-- that. If userid is primary key, one user can be of only one subtype
-- If userid and usertype make up a composite primary key, a user can be
-- of multiple types
create table userstypes (userid int, usertype int);
insert into userstypes values (1, 1), (2, 2), (3, 3);

企业和用户

create table businesses (
  id int,
  doing_business_as varchar(100), phone varchar(30)
);
insert into businesses values (1, 'Microsoft', '111-222-3333');
insert into businesses values (2, 'Toms Hardware', '111-222-3333');

-- Same as user types
-- DANGER: if you mark a user to be of type 'Basic', nothing stops that
-- user to have a business. You can use a trigger to allow only business
-- user to have an entry here
create table usersbusinesses (userid int, businessid int);
insert into usersbusinesses values (1,2), (2, 1);  

商业子类型

create table businesstypes (id int, businesstypename varchar(100));
insert into businesstypes values (1, 'Software'), (2, 'Hardware');

create table businessestypes (businessid int, businesstypes int);
insert into businessestypes values (1, 1), (2, 2);

-- DANGER: This design allows only 1 level of subtype. If a business
-- has a subtype, and that subtype has a sub-subtype and so on, this
-- design will not scale. Hierarchical design will scale but may also 
-- need performance tuning
create table businesssubtypes (id int, businesssubtypename varchar(100));
insert into businesssubtypes values (1, 'Garden Tools'), (2, 'Heavy Machine');

create table businesstypes_subtypes (businessid int, businesssubtypeid int);
insert into businesstypes_subtypes values (2,2);

根据您的应用需求,我建议您进行适当的非规范化。对于非常小,非常省力的项目,我会在一个表中制作一个扁平结构。