当前位置 : 主页 > 数据库 > mssql >

小白学Oracle第二关之第一个oracle数据库表的创建

来源:互联网 收集:自由互联 发布时间:2021-08-19
现如今在实际工作中,在数据库中创建表是经常会用到的。本文中小编主要给大家来分享一下在数据库如何通过sql语句去创建表。首先,先使用plsql连接到oracle数据库,先保证下面的服务
现如今在实际工作中,在数据库中创建表是经常会用到的。本文中小编主要给大家来分享一下在数据库如何通过sql语句去创建表。首先,先使用plsql连接到oracle数据库,先保证下面的服务是开启的。

1554890279200247.jpg

我们本次创建表的需求是:创建一张班级表,和一张学生表。

1.首先班级表作为主表也就是所谓的主键。在主表中我们这里使用的约束是primarykey 和not null


create table classinfo(
       classid number(2) primary key,
       classname varchar(10) not null       
       );

sql解析:

--create table 创建表的关键字

--classinfo 是创建的表的名字

--classid 是班级表的id 数据类型是number(2)类型,我们默认给了2个长度,我们将班级id设置为主键方便其他外键关联

--classname 是班级名字 数据类型是字符型varchar(10),我们给了默认10个字符长度,班级名的约束是不能为空

执行sql语句:

classinfo表创建成功。

2.然后我们建立一个外键,也就是关联到主键的一个表,使用的数据类型和约束请看下面的sql语句。


create table studentinfo(
       studentid number(2) primary key,
       studentname varchar(10) not null,
       studentsex char(2) check(studentsex='男' or studentsex='女'),
       studentage number(2) not null,
       studenttel number(11) unique,
       studentaddress varchar(50) default '上海',
       classid number(2) references classinfo(classid)
       );

sql语句解析:

--create table 创建表的关键字

--studentinfo();是创建学生信息表的表名

--studentid(学生id) 约束是主键 primary key

--studentname(学生姓名) 约束是 not null

--studentsex(学生性别) 约束是 check

--studentage(学生年龄) 约束是 not null

--studenttel(学生电话) 约束是 unique

--studentaddress(学生地址) 分别为学生表中的列名。

学生表studentinfo建立完成。

完整的sql语句如下:


create table classinfo(
       classid number(2) primary key,
       classname varchar(10) not null       
       );
       
create table studentinfo(
       studentid number(2) primary key,
       studentname varchar(10) not null,
       studentsex char(2) check(studentsex='男' or studentsex='女'),
       studentage number(2) not null,
       studenttel number(11) unique,
       studentaddress varchar(50) default '上海',
       classid number(2) references classinfo(classid)
       );

到此,我们创建的班级表和学生表就演示完了,是不是很简单呢?

【推荐课程:Oracle视频教程】

以上就是小白学Oracle第二关之第一个oracle数据库表的创建的详细内容,更多请关注自由互联其它相关文章!

网友评论