database - 如何实现灵活的表格

标签 database postgresql

我是新手数据库用户(不是设计师)。我想在 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/

相关文章:

PostgreSQL 将 int 值与数字字段连接起来

ruby-on-rails - rails : How to retrieve all model objects along with its foreign relation model with ActiveRecord?

java - Intellij 在存在时询问 Postgresql 依赖项

database - React Native - 连接到 PostgreSQL 数据库

mysql - 如何用 MySQL 实现物化 View ?

mysql - 奇怪的MySQL用聚合函数连接查询结果

c# - 如果用户名不在数据库中,如何显示消息框? C#

database - Redis:数据库大小与内存的比率?

mysql - MySQL 中是否有类似 PostgreSQL 的数组数据类型?

java - Hibernate 批量删除与单个删除