左连接始终包含空记录

时间:2010-12-28 18:03:36

标签: sql oracle join null left-join

我正在使用Oracle 11gR2,我正在尝试编写一个返回两个表CUSTOMERSLOCATIONS的地址数据的查询。给定客户可能(或可能不)拥有不同的位置,每个位置都有自己的地址。

我想为每位客户及其所有位置返回地址。例如,如果表包含如下数据:

CUSTOMERS
CUSTOMER_ID    ADDRESS
    1         "New York"
    2         "California"

LOCATIONS CUSTOMER_ID LOCATION_ID ADDRESS 1 1 "New Jersey"

然后我希望结果看起来像:

CUSTOMER_ID    LOCATION_ID    ADDRESS
   1                         "New York"
   1                1       "New Jersey"
   2                        "California"

我的第一个想法是这样的:

SELECT 
 CUSTOMERS.CUSTOMER_ID,
 LOCATIONS.LOCATION_ID,
 NVL(LOCATIONS.ADDRESS,CUSTOMERS.ADDRESS) ADDRESS
FROM
CUSTOMERS
 LEFT JOIN
LOCATIONS ON (CUSTOMERS.CUSTOMER_ID=LOCATIONS.CUSTOMER_ID)

问题在于,当客户确实有位置时,它不会返回具有位值数据的空值的行,因此我不会在CUSTOMERS表中找到包含该地址的行。它给了我这样的东西:

CUSTOMER_ID    LOCATION_ID    ADDRESS
   1                1       "New Jersey"
   2                        "California"

它缺少New York的{​​{1}}地址。我试过这个......

customer 1

但它给了我与第一个查询相同的结果。有没有办法返回第二个表的空记录,即使连接条件匹配?

3 个答案:

答案 0 :(得分:11)

您根本不需要加入:

SELECT  customer_id, NULL AS location_id, address
FROM    customers
UNION ALL
SELECT  customer_id, location_id, address
FROM    locations

答案 1 :(得分:1)

如果您想要加入两个表,即使存在不匹配,您也需要在已加入的列上使用IS NULL

例如。

Table 1:
CustomerID
CustomerName

Table 2:
CustomerID
CustomerEmail

Select,
CustomerID,
CustomerName,
ISNULL (CustomerEmail, NULL) AS CustomerEmail


FROM table1

LEFT JOIN table2
ON table1.CustomerID = table2.CustomerID

这将带来NULL

的结果

答案 2 :(得分:0)

您可以尝试完整的外部联接。例如:

SELECT    
CUSTOMERS.CUSTOMER_ID,   
LOCATIONS.LOCATION_ID,   
NVL(LOCATIONS.ADDRESS,CUSTOMERS.ADDRESS) ADDRESS             
FROM  CUSTOMERS   
  FULL OUTER JOIN  LOCATIONS ON (CUSTOMERS.CUSTOMER_ID=LOCATIONS.CUSTOMER_ID)