MySQL数据库表的设计

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

表的约束

主键约束

create table student(id int primary key,name varchar(40));

create table student(id int primary key auto_increment,name varchar(20));

 

唯一约束

create table student(id int primary key auto_increment,name varchar(20) u

nique);

 

非空约束

create table student(id int primary key auto_increment,name varchar(20) u

nique not null);

 

外键约束

create table teacher(id int primary key auto_increment,name varchar(20) no

t null,student_id int,constraint student_id_FK foreign key(student_id) reference

s student(id));

 

数据库的设计

一对一(一般有主从关系,把从的那个表的主键作外键约束)

create table person(id int primary key,name varchar(40));

create table idcard(id int primary key,city varchar(40),constraint id_FK foreign key(id) references person(id));

 

一对多或多对一(先设计表,在多的一方加外键)

create table department(id int primary key,name varchar(40));

create table employee(id int primary key,name varchar(40),salary decimal(8,2),department_id int,constraint department_id_FK foreign key(department_id) references department(id));

 

多对多(先设计两个表,再设计中间表(可以设联合主键)

create table teacher(id int primary key,name varchar(40),salary decimal(8,2));

create table student(id int primary key,name varchar(40));

create table teacher_student

(teacher_id int,student_id int,primary key(teacher_id,student_id),constraint teacher_id_FK foreign key(teacher_id) references teacher(id),constraint student_id_FK foreign key(student_id) references student(id));

 

自连接

create table person(id int primary key,name varchar(40),parent_id int,constraint parent_id_FK foreign key(parent_id) references person(id));


转载于:https://my.oschina.net/u/1475143/blog/214878

你可能感兴趣的:(数据库,python)