MySQL通过join实现表的关联,主要有三种方式
数据准备
create table student(stu_no int(10),name VArchar(20));
INSERT student VALUES(1,"mike");
INSERT student VALUES(2,"jin");
INSERT student VALUES(3,"tina");
INSERT student VALUES(4,"fke");
stu_no name
1 mike
2 jin
3 tina
4 fke
CREATE table score(stu_no int(10),grade int(20));
INSERT score VALUES(1,70);
INSERT score VALUES(2,80);
INSERT score VALUES(6,70);
stu_no grade
1 70
2 80
6 70
1, left join(左关联)
以左边的表为基准,将右边的表的内容添加到左边的表中,凡是左边表中有的记录新表中都有,如果右边的表没有则用 NULL 补齐
SELECT * from student a LEFT JOIN score b on a.stu_no=b.stu_no;
stu_no name stu_no grade
1 mike 1 70
2 jin 2 80
3 tina null null
4 fke null null
2, right join(右关联)
以右边的表为基准,将左边的表的内容添加到右边的表中,凡是右边表中有的记录新表中都有,如果左边的表没有则用 NULL 补齐
SELECT * from student a RIGHT JOIN score b on a.stu_no=b.stu_no;
stu_no name stu_No grade
1 mike 1 70
2 jin 2 80
null null 6 70
3, inner join(内关联)
类似于取两张表的交集,只有两个表中都有的才会在结果表中展示
SELECT * from student a INNER JOIN score b on a.stu_no=b.stu_no;
stu_no name stu_no grade
1 mike 1 70
2 jin 2 80
4, full outer join(外关联)
MySQL没有这个操作, 是针对 Oracle 的取并集操作
备注: 外关联, 等一系操作虽然没有但是可以利用查询语句构建实现出来