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.右關聯:以右表為中心,查出右表的全部數據,關聯字段值不相等則左表查出的數據顯示為空;
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表關聯的幾種常用方式