【面试题PostgreSQL】SQL内连接、外连接、半连接、笛卡尔连接区别是什么?

SQL 语句中内连接、外连接、半连接、笛卡尔连接的区别是什么?下面举个例子来说明,假设有两张表,t1 和 t2,数据如下:

postgres=# select * from t1;
 id1 | age1
-----+------
   1 |    1
   2 |    2
(2 rows)

postgres=# select * from t2;
 id2 | age2
-----+------
   2 |    2
   3 |    3
(2 rows)

1. 内连接

内连接在 join 表中查找公共元组。

隐式内连接:

postgres=# select * from t1,t2 where t1.id1=t2.id2;
 id1 | age1 | id2 | age2
-----+------+-----+------
   2 |    2 |   2 |    2
(1 row)

显式内连接,使用 join 或者 inner join:

postgres=# select * from t1 join t2 on t1.id1=t2.id2;
 id1 | age1 | id2 | age2
-----+------+-----+------
   2 |    2 |   2 |    2
(1 row)

postgres=# select * from t1 inner join t2 on t1.id1=t2.id2;
 id1 | age1 | id2 | age2
-----+------+-----+------
   2 |    2 |   2 |    2
(1 row)

2. 外连接

外连接始终获取一侧的所有数据并在另一侧找相应的匹配项,另一侧没有匹配的填充 NULL。

外连接分为左连接、右连接和全连接,左连接为 left join,右连接为 right join,全连接为 full join,如下:

postgres=# select * from t1 left join t2 on t1.id1=t2.id2;
 id1 | age1 | id2 | age2
-----+------+-----+------
   1 |    1 |     |
   2 |    2 |   2 |    2
(2 rows)


postgres=# select * from t1 right join t2 on t1.id1=t2.id2;
 id1 | age1 | id2 | age2
-----+------+-----+------
   2 |    2 |   2 |    2
     |      |   3 |    3
(2 rows)

全连接从双方获取所有数据并找匹配项,没有匹配的在对应一侧填充 NULL。

postgres=# select * from t1 full join t2 on t1.id1=t2.id2;
 id1 | age1 | id2 | age2
-----+------+-----+------
   1 |    1 |     |
   2 |    2 |   2 |    2
     |      |   3 |    3
(3 rows)

3. 笛卡尔连接(交叉连接)

笛卡尔连接又称为交叉连接,表示两个表中每行数据的任意交叉组合。

postgres=# select * from t1,t2;
 id1 | age1 | id2 | age2
-----+------+-----+------
   1 |    1 |   2 |    2
   1 |    1 |   3 |    3
   2 |    2 |   2 |    2
   2 |    2 |   3 |    3
(4 rows)

4. 半连接

内连接,外连接,全连接,笛卡尔连接都是可以获取到连接的两张表的所有字段数据,而半连接虽然有两张表进行连接,但只能获取其中一张表的字段数据,如下:

postgres=# select * from t1 where id1 in(select id2 from t2);
 id1 | age1
-----+------
   2 |    2
(1 row)

文章评论

0条评论