单字段主键
create table 表名(
字段名1 数据类型1 comment "备注信息1" primary key,
字段名2 数据类型2 comment "备注信息2"
);
多字段主键
create table 表名(
字段名1 数据类型1 comment "备注信息1",
字段名2 数据类型2 comment "备注信息2",
字段名3 数据类型3 comment "备注信息3",
primary key(字段名1,字段名2)
);
例:
create table classroom(
build varchar(5)comment "楼栋",
classroom no int comment"教室号",
seat int comment "座位数"
primary key(build,classroom no)
);
外键
constraint 字段别名一般为fk本表字段名foreign key(本表字段名)references 来源表名(来源表中字段名)
班级表中 主键: 班级名 其他字段: 人数、班长
create table class(
name varchar(20) primary key,
count int,
monitor varchar(5)comment"班长"
);
教师表 主键:教师号 其他字段:教师名
create table teacher(
no varchar(8) comment "教师号" primary key,
name varchar(20)
);
课表 外键:班级名、教师号 其他字段:课程名、....
create table timetable(
class name varchar(20),
teacher no varchar(8),
course varchar(20) comment"课程名"
constraint fk_class_name foreign key (class name) references class(name),
constraint fk_teacher_no foreign key (teacher no) references teacher(no)
);
非空: not null
唯一: unique
默认: default"默认值"
自增: auto increment
create table book(
id int comment "编号" primary key auto_increment,
name varchar(20)comment "书名" not null,
isbn varchar(30) not null unique,
is_color enum("1","2")comment "是否彩印 1是 2否"default "2"
);