The relationship between the ## multi-table
1-one (understand)
* Such as: people and identity cards
* Analysis: A person is only an ID card, an ID card corresponds to only one person.
2, many (many)
* Such as: departments and employees
* Analysis: The department has a staff of more than one employee corresponds to only one department.
3-many
* Such as: students and courses
* Analysis: A lot of students can choose their courses, a course can also be the choice of many students.
Realization relationship
1-to-many (many)
* Such as: departments and employees
* Implementation: establishing a foreign key in a multi-party, one of the points to a primary key.
2-many
* Such as: departments and employees
* Ways: by means of the third intermediate table comprising at least two fields, the two fields third table as a foreign key of the primary key of each of the two primary table.
3, one on one
* Such as: people and identity cards
* Implementation: You can add foreign key refers unique primary key in any other one.
Case:
/ * Tourism Case 1, classification table and the table is a line-to-many relationship 2, the line is many to many tables and user tables, creating an intermediate table. */ create table category( cid int primary key auto_increment, name varchar(64) not null unique ); create table routes( rid int primary key auto_increment, name varchar(128) not null unique , price double, cid int, /*constraint rou_cat_fk */foreign key (cid) references category(cid) on delete cascade on update cascade ); create table user( uid int primary key auto_increment, username varchar(32) not null unique , password varchar(32) not null ); create table favorite( rid int, date datetime, uid int, /*创建复合主键*/ primary key (rid,uid), foreign key (rid) references routes(rid), foreign key (uid) references user(uid) ); insert into category(cid, name) VALUES (1,'国外游'),(2,'国内游'); insert into routes(rid, name, price, cid) VALUES (1,'希腊游',10000.1,1),(2,'北京游',9992.1,2); insert into user (uid, username, password) values (null,'ftj','123'),(null,'lxy','456'); insert into favorite (rid, date, uid) values (1,'2020-02-08 23:59:59',1),(2,'2020-02-08 23:59:59',2); select * from user where uid = (select uid from favorite where rid = 1);