Mysql表连接:外连接(左连接右连接)与内连接

mysql中的表连接分为内连接和外连接,其中外连接又分为左连接和右连接。
内连接仅选出两张表中相互匹配的记录,外连接除此之外还会选出其他不匹配的记录,我们一般最常用内连接。
下面建2个表并插入相关数据,举例介绍表连接:

create table user_id ( id decimal(18) );
create table user_profile ( id decimal(18) , name varchar(255) ) ;

insert into user_id values (1),(2),(3),(4),(5),(6),(1);
insert into user_profile values (1, "aa"),(2, "bb"),(3, "cc"),(4, "dd"),(5, "ee"),(5, "EE"),(8, 'zz');

左连接:

select a.id id , ifnull(b.name, 'N/A') name from user_id a left join user_profile b on a.id = b.id; 

查询结果:

+------+------+
| id   | name |
+------+------+
|    1 | aa   |
|    2 | bb   |
|    3 | cc   |
|    4 | dd   |
|    5 | ee   |
|    5 | EE   |
|    6 | N/A  |
|    1 | aa   |
+------+------+
8 rows in set (0.00 sec)

user_id居左,故谓之左连接。 这种情况下,以user_id为主,即user_id中的所有记录均会被列出。分以下三种情况:
1. 对于user_id中的每一条记录对应的id如果在user_profile中也恰好存在而且刚好只有一条,那么就会在返回的结果中形成一条新的记录。如上面1, 2, 3, 4对应的情况。
2. 对于user_id中的每一条记录对应的id如果在user_profile中也恰好存在而且有N条,那么就会在返回的结果中形成N条新的记录。如上面的5对应的情况。
3. 对于user_id中的每一条记录对应的id如果在user_profile中不存在,那么就会在返回的结果中形成一条条新的记录,且该记录的右边全部NULL。如上面的6对应的情况。
不符合上面三条规则的记录不会被列出。
要查询在一个相关的表中不存在的数据, 通过id关联,要查出user_id表中存在user_profile中不存在的记录,就使用外连接:

select count(*) from user_id left join user_profile on user_id.id = user_profile.id where user_profile.id is null;

右连接:同左连接,只不过查询结果会包含所有右边表中的记录,甚至是左边表中没有匹配到的记录。

内连接:内连接仅选出两张表中互相匹配的记录,内连接查询得到的记录不会存在字段为null的记录。可以简单地认为,内链接的结果就是在左连接或者右连接的结果中剔除存在字段为NULL的记录后所得到的结果。

select *  from user_id a inner join user_profile b on a.id = b.id;

查询结果如下:

+------+------+------+
| id   | id   | name |
+------+------+------+
|    1 |    1 | aa   |
|    1 |    1 | aa   |
|    2 |    2 | bb   |
|    3 |    3 | cc   |
|    4 |    4 | dd   |
|    5 |    5 | ee   |
|    5 |    5 | EE   |
+------+------+------+
7 rows in set (0.00 sec)

内连接等价于下面的语句:

 select * from user_id a, user_profile b where a.id = b.id; 

会得到相同的查询结果:

+------+------+------+
| id   | id   | name |
+------+------+------+
|    1 |    1 | aa   |
|    1 |    1 | aa   |
|    2 |    2 | bb   |
|    3 |    3 | cc   |
|    4 |    4 | dd   |
|    5 |    5 | ee   |
|    5 |    5 | EE   |
+------+------+------+
7 rows in set (0.00 sec)

另外,MySQL不支持全连接,而sql支持全连接,也叫FULL OUTER JOIN,全连接查询会返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。

你可能感兴趣的:(mysql,数据库)