左连接,右连接,内连接
[/align][align=left]
一。准备两张表,并准备简单数据如下:
mysql> desc table_a;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(20) | NO | PRI | | |
| age | int(3) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
mysql> desc table_b;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(20) | NO | PRI | | |
| age | int(3) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
mysql> select name ,age from table_a;
+------+-----+
| name | age |
+------+-----+
| a | 1 |
+------+-----+
mysql> select name ,age from table_b;
+------+-----+
| name | age |
+------+-----+
| a | 1 |
| b | 2 |
+------+-----+
二。左连接 与右连接 测试
左连接,以左边表为基准
测试1:
mysql> select a.name,a.age from table_a a left join table_b b on a.name=b.name;
+------+-----+
| name | age |
+------+-----+
| a | 1 |
+------+-----+
1 row in set
测试2:
依然是左连接,两表换下位置:
mysql> select a.name,a.age from table_b a left join table_a b on a.name=b.name;
+------+-----+
| name | age |
+------+-----+
| a | 1 |
| b | 2 |
+------+-----+
2 rows in set
测试3:
右连接,以右表为基准
mysql> select a.name,a.age from table_a a right join table_b b on a.name=b.name;
+------+------+
| name | age |
+------+------+
| a | 1 |
| NULL | NULL |
+------+------+
2 rows in set
测试4:
依然是右连接,两表互换位置
mysql> select a.name,a.age from table_b a right join table_a b on a.name=b.name;
+------+-----+
| name | age |
+------+-----+
| a | 1 |
+------+-----+
1 row in set
左外连接是以左边的表为基准。通俗的讲,先将左边的表全部显示出来,
需要注意的是测试2与测试3的结果不一样。
测试仪5:
mysql> select a.name,a.age from table_a a inner join table_b b on a.name=b.name;
+------+-----+
| name | age |
+------+-----+
| a | 1 |
+------+-----+
1 row in set
测试仪6
mysql> select a.name,a.age from table_b a inner join table_a b on a.name=b.name;
+------+-----+
| name | age |
+------+-----+
| a | 1 |
+------+-----+
1 row in set
内连接就是只取出符合过滤条件的记录 也就是t1.id=t2.id 那么符合t1.id=t2.id的记录只有id=1这一条,所以只显示一条。 不像外连接,是将你作为基准的表(左外连接就是左边表为基准,右外连接就是右边表为基准)的所有行都显示出来。而且无关乎表的先后顺序。