正确的SQL创建表语句?

时间:2015-03-26 02:47:10

标签: sql oracle create-table

我一直被困在我正在处理的最终表/数据字典上,而且我对create table语句的语法不太确定。

数据字典:

表名:注册

Sid(列名)
NUMBER(数据类型)
5(长度)
空白(非空)
Y(PK)
Y(FK)
空白支票)

Csecid(列名)
NUMBER(数据类型)
8(长度)
空白(非空)
Y(PK)
Y(FK)
空白支票)

等级(列名)
CHAR(数据类型)
1(长度)
空白(非空)
空白(PK)
空白(FK)
A,B,d,d,F,I,W(支票)。

备注:
Sid也被定义为STUDENT表上的PK。
Csecid也被定义为COURSE_SECTION表上的PK。

我不知道如何在Create table语句中将Sid和Csecid定义为PK和FK。请帮忙。谢谢!

1 个答案:

答案 0 :(得分:0)

根据我的理解,您需要为表EnrollmentStudent创建映射表Course_Section,因为StudentCourse_Section具有多对多关系。

下面列出了示例模式并创建了表查询:

-- Create Student Table
create table student(sid number(5) primary key, sname varchar2(100),
                     dob date);

-- Insert some data
insert into student values(1,'student1','01-feb-1990');
insert into student values(2,'student2','01-mar-1990');
insert into student values(3,'student3','01-apr-1990');
insert into student values(4,'student4','01-may-1990');
commit;

-- Create Course_Section Table
create table course_section(csecid number(8) primary key, 
                            csname varchar2(30));

-- Insert some data
insert into course_section values(115,'CS1');
insert into course_section values(116,'CS2');
insert into course_section values(117,'CS3');
insert into course_section values(118,'CS4');
insert into course_section values(119,'CS5');
commit;

-- Since student and course_section have many-to-many relationship
-- One student can enroll to many courses
-- One course can be associated with many students
-- They need to be related using separate table
create table enrollment(sid number(5) not null, 
                        csecid number(8) not null, 
                        grade char(1) not null, 
                        constraint e_pk primary key(sid, csecid), 
                        foreign key (sid) references student(sid), 
                        foreign key (csecid) references course_section(csecid), 
           constraint gc_constraint check (grade in ('A','B','C','D','F','I','W')));

-- Insert some records in enrollment
insert into enrollment values(1,115,'D');
insert into enrollment values(2,118,'C');
insert into enrollment values(1,118,'C');
insert into enrollment values(2,117,'A');
insert into enrollment values(4,116,'B');
insert into enrollment values(3,118,'I');
insert into enrollment values(4,118,'W');
commit;

检查this sqlfiddle以了解更多信息。