功能:join 的功能是将两个或以上的表的字段按照一定条件结合到一个表上。
用例:
学生表
id | name | cid |
---|---|---|
1 | 男1 | 1 |
2 | 女1 | 2 |
3 | middle | 8 |
班级表
id | name | institute |
---|---|---|
1 | 计算机1541 | 1 |
2 | 计算机1542 | 1 |
3 | 英语 | 2 |
通过这两个表来进行测试。
1.交叉连接(笛卡尔积):数量为两个表数据的乘积。
select * from user cross join class;
select * from user,class;
2.左连接:返回左边表的所有行和满足on条件的右边行。
select * from user left join class on user.cid=class.id;
id | name | cid | id1 | name1 | institute |
---|---|---|---|---|---|
1 | 男1 | 1 | 1 | 计算机1541 | 1 |
2 | 女2 | 3 | 3 | 英语 | 2 |
3 | middle | 8 |
3.右连接:返回右边表的所有行和满足on条件的左边行。
select * from user right join class on user.cid=class.id;
id | name | cid | id1 | name1 | institute |
---|---|---|---|---|---|
1 | 男1 | 1 | 1 | 计算机1541 | 1 |
2 | 计算机1542 | 1 | |||
3 | 女2 | 3 | 3 | 英语 | 2 |
4.内连接:返回两表的交集部分。
select * from user inner join class on user.cid=class.id;
id | name | cid | id1 | name1 | institute |
---|---|---|---|---|---|
1 | 男1 | 1 | 1 | 计算机1541 | 1 |
2 | 女2 | 3 | 3 | 英语 | 2 |
5.全外连接:mysql中没有全外连接的执行语句,可以使用两个外连接结合使用推算而出。
select * from user left join class on user.cid=class.id
UNION
select * from user right join class on user.cid=class.id
id | name | cid | id1 | name1 | institute |
---|---|---|---|---|---|
1 | 男1 | 1 | 1 | 计算机1541 | 1 |
2 | 女2 | 3 | 3 | 英语 | 2 |
3 | middle | 8 | |||
2 | 计算机1542 | 1 |
6.自然连接
请参考 https://blog.youkuaiyun.com/elearnings/article/details/10253437