没有任何连接条件的 FULL OUTER JOIN

FULL OUTER JOIN without any join conditions

我有两张桌子

t1:

+--------------+-------------+--------------+
| Product Name |   Issue #   |  Risk Level  |
+--------------+-------------+--------------+
| Product1     | Incident#45 | Risk Level 2 |
| Product2     | Incident#23 | Risk Level 3 |
| Product3     | Incident#98 | Risk Level 1 |
+--------------+-------------+--------------+

t2:

+----------+----------------+
| Org Code | Monthly Output |
+----------+----------------+
|      598 |           2000 |
|      412 |            100 |
|      598 |           2500 |
+----------+----------------+

我想将其合并为一个 "outer join" 来创建:

+--------------+-------------+--------------+----------+----------------+
| Product Name |   Issue #   |  Risk Level  | Org Code | Monthly Output |
+--------------+-------------+--------------+----------+----------------+
| Product1     | Incident#45 | Risk Level 2 | (null)   | (null)         |
| Product2     | Incident#23 | Risk Level 3 | (null)   | (null)         |
| Product3     | Incident#98 | Risk Level 1 | (null)   | (null)         |
| (null)       | (null)      | (null)       | 598      | 2000           |
| (null)       | (null)      | (null)       | 412      | 100            |
| (null)       | (null)      | (null)       | 598      | 2500           |
+--------------+-------------+--------------+----------+----------------+

t1t2 没有类似的专栏供我加入。有什么方法可以将这些表连接在一起吗?

您可以使用:

select l1.*, l2.*
from l1 full join
     l2
     on 1 = 0;   -- never true

您可以在此处使用 union all。在我看来,这是对您的问题进行查询的最自然方式。

它还具有可广泛移植的优点:大多数数据库都支持 union all - full join 并非如此,尽管几十年来一直是 SQL 标准的一部分,尚不支持所有主要产品(例如 MySQL)。

select product_name, issue#, risk_level, null org_code, null monthly_output from t1
union all
select null, null, null, org_code, monthly_output from t2

我认为 UNION ALLJOIN 更有效,最重要的是,更具可读性。

SELECT
    ProductName
    , IssueNumber
    , RiskLevel
    , NULL AS OrgCode
    , NULL AS MonthlyOutput
FROM t1

UNION ALL

SELECT
    NULL AS ProductName
    , NULL AS IssueNumber
    , NULL AS RiskLevel
    , OrgCode
    , MonthlyOutput
FROM t2