MySQL表关联的几种常用方式
工作中我们经常会使用表与表关联来查询数据,如果对join 不熟悉,可能会得到我们不想要的节过,这里就来介绍下join的几种常用方法:
建表及插入数据,
CREATE TABLE school
(sch_id
int(11) NOT NULL AUTO_INCREMENT,sch_name
varchar(50) NOT NULL,sch_addr
varchar(100) DEFAULT NULL,
PRIMARY KEY (sch_id
)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
CREATE TABLE student
(st_id
int(11) NOT NULL AUTO_INCREMENT,st_name
varchar(20) NOT NULL,age
smallint(6) DEFAULT NULL,hight
int(5) DEFAULT NULL,sch_id
int(11) DEFAULT NULL,
PRIMARY KEY (st_id
),
KEY sch_id
(sch_id
)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 ;
INSERT INTO school
VALUES (1,'南开大学','南开'),(2,'*财经大学','北京'),(3,'香港理工大学','香港'),(4,'西安交通大学','西安'),(5,'悉尼大学','悉尼'),(6,'曼彻斯特大学','曼彻斯特'),(8,'延安抗日军政大学','延安');
INSERT INTO student
VALUES (1,'王晓阳',26,168,6),(2,'王楠',28,162,2),(3,'杨振宇',30,178,1),(4,'苗昕',28,162,3),(5,'张诗雨',27,171,5),(8,'李倩',28,162,4),(9,'蒋结石',26,178,7);
1.左关联:以左表为中心,查出左表的全部数据,关联字段值不相等则右表查出的数据显示为空;
select * from school a left join student b on a.sch_id=b.sch_id;
2.右关联:以右表为中心,查出右表的全部数据,关联字段值不相等则左表查出的数据显示为空;
select * from school a right join student b on a.sch_id=b.sch_id;
3.内关联:查出两表关联字段等值的数据
select * from school a inner join student b on a.sch_id=b.sch_id;
4.查出只属于左表的数据
select * from school a left join student b on a.sch_id=b.sch_id where b.st_id is null;
5.查出只属于右表的数据
select * from school a right join student b on a.sch_id=b.sch_id where a.sch_id is null;
6.查出全部数据
select * from school a left join student b on a.sch_id=b.sch_id union select * from school a right join student b on a.sch_id=b.sch_id;
7.查出左表和右表关联不相等的数据
select * from school a left join student b on a.sch_id=b.sch_id where b.st_id is null union select * from school a right join student b on a.sch_id=b.sch_id where a.sch_id is null;