MySQL 多表结构的创建与分析
Posted z1115230598
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL 多表结构的创建与分析相关的知识,希望对你有一定的参考价值。
=====================多对一===================== create table press( id int primary key auto_increment, name varchar(20) ); create table book( id int primary key auto_increment, name varchar(20), press_id int not null, foreign key(press_id) references press(id) on delete cascade on update cascade ); insert into press(name) values (‘北京工业地雷出版社‘), (‘人民音乐不好听出版社‘), (‘知识产权没有用出版社‘) ; insert into book(name,press_id) values (‘九阳神功‘,1), (‘九阴真经‘,2), (‘九阴白骨爪‘,2), (‘独孤九剑‘,3), (‘降龙十巴掌‘,2), (‘葵花宝典‘,3) ; sql示例
create table author( id int primary key auto_increment, name varchar(20) ); #这张表就存放作者表与书表的关系,即查询二者的关系查这表就可以了 create table author2book( id int not null unique auto_increment, author_id int not null, book_id int not null, constraint fk_author foreign key(author_id) references author(id) on delete cascade on update cascade, constraint fk_book foreign key(book_id) references book(id) on delete cascade on update cascade, primary key(author_id,book_id) ); #插入四个作者,id依次排开 insert into author(name) values(‘egon‘),(‘alex‘),(‘yuanhao‘),(‘wpq‘); #每个作者与自己的代表作如下 egon: 九阳神功 九阴真经 九阴白骨爪 独孤九剑 降龙十巴掌 葵花宝典 alex: 九阳神功 葵花宝典 yuanhao: 独孤九剑 降龙十巴掌 葵花宝典 wpq: 九阳神功 insert into author2book(author_id,book_id) values (1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (2,1), (2,6), (3,4), (3,5), (3,6), (4,1) ; sql示例
create table customer( -> id int primary key auto_increment, -> name varchar(20) not null, -> qq varchar(10) not null, -> phone char(16) not null -> ); create table student( -> id int primary key auto_increment, -> class_name varchar(20) not null, -> customer_id int unique, #该字段一定要是唯一的 -> foreign key(customer_id) references customer(id) #外键的字段一定要保证unique -> on delete cascade -> on update cascade -> ); #增加客户 mysql> insert into customer(name,qq,phone) values -> (‘韩蕾‘,‘31811231‘,13811341220), -> (‘杨澜‘,‘123123123‘,15213146809), -> (‘翁惠天‘,‘283818181‘,1867141331), -> (‘杨宗河‘,‘283818181‘,1851143312), -> (‘袁承明‘,‘888818181‘,1861243314), -> (‘袁清‘,‘112312312‘,18811431230) mysql> #增加学生 mysql> insert into student(class_name,customer_id) values -> (‘脱产1班‘,3), -> (‘周末1期‘,4), -> (‘周末1期‘,5) -> ; sql示例
以上是关于MySQL 多表结构的创建与分析的主要内容,如果未能解决你的问题,请参考以下文章