我是新手数据库用户(不是设计师)。我想在 postgres 数据库中实现以下项目。
我想实现一个包含以下信息的数据库
Table1
Classroom | Classroom Type | AV System | Student1 | Student2 | ... | Student36
1A | 'Square' | 1 | 'Anson' | 'Antonie'| ... | 'Zalda'
1B | 'Rectangle' | 2 | 'Allen' | 'Andy' | ... | 'Zeth'
还有一张表用来存放每个学生的座位表,这就是我创建另一张表的原因
Table2
Classroom Type | Student1 Position | Student2 Position | ... | Student36 Position
'Square' | (1,1) | (1,2) | ... | (6,6)
'Rectangle' | (1,1) | (1,2) | ... | (4,9)
Table3
AV System | TV | Number of Speaker
1 | 'LCD' | 2
2 | 'Projector' | 4
这个实现的原因是绘制一个座位图。但是我认为这不是一个好的实现。因此,我想找到另一种方法,在我想扩大规模时给我一些灵 active 。
提前致谢。
最佳答案
这不是关系数据库的工作方式。在关系数据库中,您不会重复属性,而是创建 1:N 关系。此过程称为规范化,其主要目标之一是防止数据重复。
据我所知,以下结构可以满足您的要求:
-- a table to store all possible classroom types ("Square", "Rectangle", ...)
create table classroom_type
(
type_id integer not null primary key,
type_name varchar(20) not null,
unique (type_name)
);
-- a table to store all classrooms
create table classroom
(
room_id integer not null primary key,
room_name varchar(5) not null,
room_type integer not null references classroom_type,
unique (room_name)
);
-- a table containing all students
create table student
(
student_id integer not null primary key,
student_name varchar(100) not null
--- ... possibly more attributes like date of birth and others ....
);
-- this table stores the combinations which student has which position in which classroom
create table seating_plan
(
student_id integer not null references student,
room_id integer not null references room,
position varchar(10) not null,
primary key (student_id, room_id), -- make sure the same student is seated only once in a room
unique (room_id, position) -- make sure each position is only used once insid a room
);
我为 ID 列使用了 integer
,但您很可能希望使用 serial
自动为它们创建唯一值。
很可能该模型需要扩展以包括一个学年。因为学生 Allen 今年可能在 1A 房间,但明年在 3C 房间。这将是 seat_plan
表的另一个属性(并且将成为主键的一部分)
关于database - 如何实现灵活的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18506854/