我正在尝试设计一个具有超级类型/子类型的数据库。我有以下用户:
所有三个用户都共享一个公共表(用户),其中存储姓名、电子邮件、密码等字段。但是,业务用户有一个单独的表(业务),其中存储业务字段(如business_name、business_license、business_email等)。我的问题是,我的业务用户自己被分成了5个或更多个类别。
我的业务用户是这样分裂的:
有一点要提到的是,我希望将所有这些业务用户存储在某个表中,这样就可以轻松地添加和删除位置,而不会在应用程序级别上造成很大的混乱。
我目前设计了这个数据库,但我对它并不满意。有没有更好的方法?
发布于 2015-08-10 19:35:18
你的设计很不错。我喜欢它。将一些数据放入其中并编写一些查询。如果你如此渴望的话,你可以让它正常化一点。下面是您可以使用的SQLFiddle,http://sqlfiddle.com/#!9/b0711/3和下面的语句。
用户和类型
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);
根据您的应用程序需求,我建议您进行适当的去规范化。对于非常小的、非常低工作量的项目,我会在一个表中创建一个平面结构。
https://stackoverflow.com/questions/31931222
复制