在SQL中,有n中连接,有时候闹的晕晕乎乎的,现在整理出来:
1、连接
select * from table1, table2;
select * from table1 cross join table2;
这种连接执行的结果是:
table1中的每一条记录都对应table2中的记录,像这样:
table1 table2
1 ------- -1
2 ---------1
3---------1
1---------2
2---------2
3---------2
2、自连接
就是把一个表当两个表看,同表内进行连接
select a.name, b.name from table1 a, table1 b
where a.name = b.name;
3、内连接(inner join)
select a.name, b.name from table1 a inner join table2 b on a.name = b.name;
格式是:表1 inner join 表2 on 条件
等价于:
select a.name, b.name from table1 a, table2 b where a.name = b.name;
4、外连接(outer join)
允许限制一张表中的行,而不限制另外一张表中的行。
注意:外连接不一定非要有外键约束
4.1、左外连接(left outer join)
select * from table1 a left outer join table2 b on a.name = b.name;
列出table1中所有的项,table2中匹配不上的用NULL表示
结果:
4.2、右外连接(right outer join)
select * from table1 a right outer join table2 b on a.name = b.name;
和左外连接相反,列出table2中所有项,table1中不匹配的用NULL表示
结果:
4.3、全连接(full join)
返回两个表中的匹配和不匹配的所有记录。
不是所有数据库都支持
1、连接
select * from table1, table2;
select * from table1 cross join table2;
这种连接执行的结果是:
table1中的每一条记录都对应table2中的记录,像这样:
table1 table2
1 ------- -1
2 ---------1
3---------1
1---------2
2---------2
3---------2
2、自连接
就是把一个表当两个表看,同表内进行连接
select a.name, b.name from table1 a, table1 b
where a.name = b.name;
3、内连接(inner join)
select a.name, b.name from table1 a inner join table2 b on a.name = b.name;
格式是:表1 inner join 表2 on 条件
等价于:
select a.name, b.name from table1 a, table2 b where a.name = b.name;
4、外连接(outer join)
允许限制一张表中的行,而不限制另外一张表中的行。
注意:外连接不一定非要有外键约束
4.1、左外连接(left outer join)
select * from table1 a left outer join table2 b on a.name = b.name;
列出table1中所有的项,table2中匹配不上的用NULL表示
结果:
id | name | age | id | name | age |
1 | fred | 22 | 1 | fred | 22 |
2 | acea | 23 | 2 | acea | 23 |
3 | tom | 23 | NULL | NULL | NULL |
4.2、右外连接(right outer join)
select * from table1 a right outer join table2 b on a.name = b.name;
和左外连接相反,列出table2中所有项,table1中不匹配的用NULL表示
结果:
id | name | age | id | name | age |
1 | fred | 22 | 1 | fred | 22 |
2 | acea | 23 | 2 | acea | 23 |
NULL | NULL | NULL | 4 | mary | 24 |
4.3、全连接(full join)
返回两个表中的匹配和不匹配的所有记录。
不是所有数据库都支持