MySQL表关联的常用方式有哪几种 - 行业资讯

本文主要给大家介绍MySQL表关联的常用方式有哪几种,文章内容都是笔者用心摘选和编辑的,具有一定的针对性,对大家的参考意义还是比较大的,下面跟笔者一起了解下MySQL表关联的常用方式有哪几种吧。

建表及插入数据,
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;

MySQL表关联的常用方式有哪几种 - 行业资讯

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;

看完以上关于MySQL表关联的常用方式有哪几种,很多读者朋友肯定多少有一定的了解,如需获取更多的行业知识信息 ,可以持续关注我们的行业资讯栏目的。

赞(0)
未经允许不得转载:主机测评网 » MySQL表关联的常用方式有哪几种 - 行业资讯
分享到: 更多 (0)