目录
参考表:
学员信息表:person | ||
id | name | age |
1 | atom | 19 |
2 | atom2 | 19 |
3 | atom3 | 21 |
4 | atom4 | 21 |
5 | atom5 | 25 |
6 | atom6 | 25 |
班级列表:class | ||
id | name | class |
1 | atom | class1 |
2 | atom2 | class1 |
3 | atom3 | class2 |
4 | atom4 | class2 |
5 | atom5 | class3 |
6 | atom6 | class3 |
1、左联结(a LEFT JOIN b on 条件)
如果我们想查询人员表的全部值,班级表中只与人员表相匹配的值,应该怎么查呢?
这时候就需要用到左链接了,查询范围可以看这个图。
SQL怎么写呢?
SELECT person.name,person.age,class.class from person LEFT JOIN class on person.name = class.name
搜索人员表与班级表中的姓名相同的数据(交集数据),然后以人员表为主展示出来(如果值相同就展示出来,值不相同就展示null)
2、右联结(a RIGHT JOIN b on 条件)
如果我们想查询班级表的全部值,和班级表中只与人员表相匹配的值,应该怎么查呢?
这时候就需要用到右链接了,查询范围可以看这个图。
SQL怎么写呢?
SELECT person.name,person.age,class.class,class.name from person RIGHT JOIN class on person.name = class.name
搜索人员表与班级表中的姓名相同的数据(交集数据),然后以班级表为主展示出来(如果值相同就展示出来,值不相同就展示null)