Sql(structured query language)结构化查询语言:包含
DDL(Database definition language)数据库定义语言,
DQL(Database query language)数据库查询语言,
DML(Database manipulation language)数据库操作语言
DCL(Databse control language)数据库控制语言等
DDL:
1.创建数据库表之前
1.设计:三范式
第一范式:表中的元素原子性,列不可再分。比如student info当中有名字+年龄,就是可分不符合原子性
第二范式:在第一范式的基础上,每张表中必须含有主键:--主键(主键元素每张表中不可以相同)
第三范式:在第二范式的基础上,表中每个元素需要相互独立,不存在函数关系
2.本表中的外键只能是其它表中的主键。
3.分析表与表之间的关系:一对多1-->n,一对一,还是多对多
1---1 在哪个表中封装外键都可以,视具体情况而定
1--->n 在多的一方封装1的一方的主键。减少数据冗余
n--n 需要第三张表过渡
/*2.创建表(不区分大小写)*/
/*主键约束一*/
Create table tablename
(
/*类名 类型名*/
/*设置主键,在需要设置主键的类名后面加 primary key*/
stuNo int primary key
)
/*主键约束二*/
Create table tablename
(
/*类名 类型名*/
stuNo int ,
primary key(stuNo)
)
/*主键约束三*/
Create table tablename
(
/*类名 类型名*/
stuNo int
)
ALTER table tablename add constraint pk_name PRIMARY KEY (stuNo);
/*删除表*/
drop table tablename;
/*数据库的常用数据类型
1.整型 int、integer
2.浮点型double、float、decimal(n,m)--长度为n,小数部分m位
3.字符型char(m)、varchar(m)char固定长度为m,varchar则是不超过m,有多少分配多少。
char浪费资源但是搜索速度略快于varchar
4.日期型date、datetime date是年月日 datetime是年月日时分秒
5.长字符串 text
6.大数据二进制 blob
*/
/*非空约束*/
Create table tablename
(
stuNo int not null
)
/*默认值约束-1*/
Create table tablename
(
stuNo int default 1
)
/*默认值约束-2*/
Create table tablename
(
stuNo int
)
--添加一个字段
alter table tablename add stuName varchar(20) default 'abc';
--让一个表中某一类型的值全都不同,除了使用主键,还可以使用unique
--唯一性约束一unique
/* 创建学生表 */
create TABLE student
(
stuno int PRIMARY KEY,
stuname varchar(255) unique not null,/*登录系统用户名*/
)
--此处用户名唯一且不空
--唯一性约束2
create TABLE student
(
stuno int PRIMARY KEY,
stuname varchar(255) not null/*登录系统用户名*/
)
alter table student add constraint uq_stuname UNIQUE (stuname);
drop table if EXISTS student;
--外键约束
--创建课程表,学生与课程表是n-n 的关系,创建一个成绩表。
create TABLE student
(
stuno int,
stuname varchar(255) not null COMMENT '登录名',/*登录系统用户名*/
realname varchar(255) not null,/*真实姓名*/
stusex char(3) not null,
stuage int default 20,
tel varchar(255) default 'xxxxx',
birthday date,
height double,
primary key (stuno),/*集中添加约束*/
unique(stuname)
)
create table course
(
cid int primary key ,
cname varchar(255),
remark VARCHAR(255)
)
--外键约束1
create table score
(
sid int PRIMARY key not null,
stid int ,
FOREIGN key(stid) REFERENCES student(stuno)
)
--外键约束2
alter table score add cid int;
alter table score add CONSTRAINT fk_fkname FOREIGN key (cid) REFERENCES course(cid);
--外键约束3
drop table if EXISTS score;
create table score
(
sid int PRIMARY key not null,
stid int not NULL REFERENCES student(stuno)
)