主鍵約束數據庫
create table student(id int primary key,name varchar(40));spa
create table student(id int primary key auto_increment,name varchar(20));設計
惟一約束ci
create table student(id int primary key auto_increment,name varchar(20) urem
nique);it
非空約束table
create table student(id int primary key auto_increment,name varchar(20) uim
nique not null);數據
外鍵約束tab
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));