Relationship tables and tables

One, one to many: many foreign key in one record, a record of the first one, one of the many foreign key to a dependent one of the primary key.

    Many-to-: nature is the same in turn can be.

create table dept(
id int PRIMARY KEY AUTO_INCREMENT COMMENT '部门id',
VARCHAR dept_name ( 30) the NOT NULL the COMMENT 'department name'
)

CREATE TABLE emp(
eid int PRIMARY key auto_increment COMMENT '员工id',
VARCHAR emp_name ( 30) the NOT NULL the COMMENT 'Employee Name' ,
did int ,
FOREIGN KEY(did) REFERENCES dept (id) 
)

Second, one to one:

 2.1 The first way: that is, on the basis of many of the more than one foreign key constraints unique plus unique 

create table wife (
wid int PRIMARY key  auto_increment ,
wname VARCHAR(30) NOT NULL 
)

create table husband (
hid int PRIMARY key  auto_increment ,
hname VARCHAR(30) NOT NULL ,
wid int UNIQUE,
FOREIGN key(wid)  REFERENCES wife(wid)
)

2.2 The second way: Let the primary key of a table at the same time as the primary key of another table while a primary key of this table can not be incremented,

Because it is a foreign key can be repeated, but it is the primary key can not be repeated this in turn will become one.

create table person (
pid int PRIMARY key auto_increment,
pname VARCHAR(30) NOT NULL 
)

CREATE TABLE card (
cid int PRIMARY key ,
num VARCHAR(18),
FOREIGN key(cid) REFERENCES person(pid)
)

Third, many-create the table: as the primary key to making this pair will not be repeated,

create table teacher (
tid int PRIMARY key auto_increment,
tname VARCHAR(30) NOT NULL 
)

create table teacher_student(
time int ,
sid int ,
Key a PRIMARY (TID, SID) the COMMENT 'primary key' ,
FOREIGN key (time) REFERENCES teacher (time),
FOREIGN key (sid) REFERENCES student(sid)
)

create table student (
sid int PRIMARY key auto_increment,
sname VARCHAR(30) NOT NULL 
)

 

Guess you like

Origin www.cnblogs.com/ych961107/p/12000928.html