多表查询经典例子
一对多或称为多对一
三张表:出版社,作者信息,书
一对多(或多对一):一个出版社可以出版多本书
关联方式:foreign key
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)
#1 操作文件夹(库)
增
create database db1 charset utf8;
查
show databases;
show create database db1;
改
alter database db1 charset gbk;
删
drop database db1;
#2 操作文件(表)
切换到文件夹下:use db1
增
create table t1(id int,name char(10))engine=innodb;
create table t2(id int,name char(10))engine=innodb default charset utf8;
查
show tables;
show create table t1;
desc t1;#查看表结构
改
alter table t1 add age int;
alter table t1 modify name char(12);
删
drop table t1;
#3 操作文件的一行行内容(记录)
增
insert into db1.t1 values(1,'egon1'),(2,'egon2'),(3,'egon3');
insert into db1.t1(name) values('egon1'),('egon2'),('egon3');
查
select * from t1;
select name from t1;
select name,id from t1;
改
update t1 set name='SB' where id=4;
update t1 set name='SB' where name='alex';
删
delete from t1 where id=4;
#对于清空表记录有两种方式,但是推荐后者
delete from t1;
truncate t1; #当数据量比较大的情况下,使用这种方式,删除速度快
#自增id
create table t5(id int primary key auto_increment,name char(10));
create table t4(id int not null unique,name char(10));
insert into t5(name) values
('egon5'),
('egon6'),
('egon7'),
('egon8'),
('egon9'),
('egon10'),
('egon11'),
('egon12'),
('egon13');
create table t7 select * from t5 where 1=2;
alter table t7 modify id int primary key auto_increment;
flush privileges;
revoke select on db1.* from 'alex'@'%';