请稍候,加载中....

SQL 全连接

FULL JOIN 

FULL OUTER JOIN 关键字只要左表(table1)和右表(table2)其中一个表中存在匹配,则返回行.

FULL OUTER JOIN 关键字结合了 LEFT JOIN 和 RIGHT JOIN 的结果。SELECT column_name(s)

FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

 


演示数据库

在猿变手册教程中,我们将使用 yuanbian 数据库。

下面是选自 "articles" 表的数据:

+----+-----------------+-----------+--------+---------------------+
| id | title           | author    | a_type | pub_date            |
+----+-----------------+-----------+--------+---------------------+
|  1 | hadoop简介      | 大猿      |    311 | 2003-01-05 11:23:00 |
|  2 | python元类      | 小猿      |    163 | 2003-01-11 13:00:01 |
|  3 | HTML基础        | 猿大头    |    497 | 2004-03-09 12:00:00 |
|  4 | Javascript      | 猿媛      |     20 | 2005-11-03 17:34:12 |
|  5 | ETL快速入门     | 猿媛      |      3 | 2005-11-07 18:40:00 |
|  6 | 异步编程        | 大猿      |      3 | 2005-11-07 18:45:00 |
+----+-----------------+-----------+--------+---------------------+

下面是 "article_view_log" 网站访问记录表的数据:

+--------+------+-------+------------+
| log_id | aid  | count | log_date   |
+--------+------+-------+------------+
|      1 |    1 | 100   | 2005-03-01 |
|      2 |    3 | 140   | 2005-03-01 |
|      3 |    5 | 303   | 2005-03-01 |
|      4 |    2 | 120   | 2005-03-02 |
|      5 |    4 | 180   | 2005-03-02 |
|      6 |    5 | 430   | 2005-03-02 |
|      7 |    1 | 210   | 2005-03-02 |
|      8 |    4 | 330   | 2005-03-03 |
|      9 |    2 | 210   | 2005-03-03 |
+--------+------+-------+------------+

 


FULL JOIN 示例

下面的 SQL 语句选取所有网站访问记录。

MySQL中不支持 FULL OUTER JOIN,你可以在 SQL Server 测试以下实例。

SELECT articles.title, article_view_log.count, article_view_log.log_date
FROM articles
FULL OUTER JOIN article_view_log
ON articles.id=article_view_log.aid
ORDER BY article_view_log.count DESC;

注释:FULL OUTER JOIN 关键字返回左表(articles)和右表(article_view_log)中所有的行。如果 "articles" 表中的行在 "article_view_log" 中没有匹配或者 "article_view_log" 表中的行在 "articles" 表中没有匹配,也会列出这些行。

 


MySQL FULL JOIN

使用union结合left join与right join结果

(SELECT articles.title, article_view_log.count, article_view_log.log_date
FROM articles
LEFT JOIN article_view_log
ON articles.id=article_view_log.aid)
UNION
(SELECT articles.title, article_view_log.count, article_view_log.log_date 
FROM articles 
RIGHT JOIN article_view_log 
ON articles.id=article_view_log.aid)
ORDER BY count DESC;

输出结果:

+-----------------+-------+------------+
| title           | count | log_date   |
+-----------------+-------+------------+
| ETL快速入门     | 430   | 2005-03-02 |
| Javascript      | 330   | 2005-03-03 |
| ETL快速入门     | 303   | 2005-03-01 |
| hadoop简介      | 210   | 2005-03-02 |
| python元类      | 210   | 2005-03-03 |
| Javascript      | 180   | 2005-03-02 |
| HTML基础        | 140   | 2005-03-01 |
| python元类      | 120   | 2005-03-02 |
| hadoop简介      | 100   | 2005-03-01 |
| 异步编程        | NULL  | NULL       |
+-----------------+-------+------------+

 


Python学习手册-