【发布时间】:2015-07-17 13:41:42
【问题描述】:
我有三个表(简化版 - 整个画面有点复杂)。
TABLE: CUSTOMER TABLE: PURCHASE1 TABLE: PURCHASE2
=============== ======================= =======================
CustomerID CustomerID | ProductID CustomerID | ProductID
--------------- ------------|---------- ------------|----------
1 1 | 51 1 | 81
2 1 | 52 1 | 82
3 2 | 52 1 | 83
我知道表格结构不是最好的,但这不是我需要帮助的地方。如果这有助于提供上下文,购买表中的产品属于不同类型。
我正在尝试加入表格,使用如下查询:
Select
customer.customerid, purchase1.productid as P1,
purchase2.productid as P2
From
customer
Left join
purchase1 on customer.customerid = purchase1.customerid
Left join
purchase2 on customer.customerid = purchase2.customerid
Where
customer.customerid = 1;
这会产生以下内容:
CustomerID | P1 | P2
--------------------
1 | 51 | 81
1 | 51 | 82
1 | 51 | 83
1 | 52 | 81
1 | 52 | 82
1 | 52 | 83
我怎样才能让它这样做呢?
CustomerID | P1 | P2
-----------|------|---
1 | 51 | null
1 | 52 | null
1 | null | 81
1 | null | 82
1 | null | 83
第一个表对于 P1 和 P2 的每个组合都有一行。第二个表只有一行用于每个客户-产品组合。
我可以在不使用 UNION 的情况下执行此操作吗?我问的原因是因为查询将变得更加复杂,使用不在 PURCHASE1 或 PURCHASE2 中的其他行的列。
如果我必须使用 UNION,我该怎么做才能让我仍然可以从其他表中进行选择并在我的查询中包含其他列?
【问题讨论】:
标签: sql oracle tsql oracle11g oracle10g