sql左外连接与约束列

时间:2014-01-17 10:12:32

标签: sql postgresql outer-join right-join

这是SQL,'aal_county_zip'有2个zipcodes的条目,而'us_zip'有15个zipcodes。要求是获得15行,只有2行具有来自'aal_county_zip'的数据。它的工作方式类似于普通连接。如何更改SQL / Table结构以使其工作。我还想添加下面评论的条件。

SELECT DISTINCT a.zcta5ce10 AS zipcode, 
                c.report_year, 
                c.aal 
FROM   aal_county_zip c 
       RIGHT OUTER JOIN us_zip a 
                     ON ( c.zip = a.zcta5ce10 ) 
WHERE  Lower(c.name) = Lower('alachua') 
--and c.report_year=2009 
ORDER  BY c.report_year DESC 

2 个答案:

答案 0 :(得分:1)

查询中的WHERE Lower(c.name) = Lower('alachua')会将外部联接变为内部联接,因为它会阻止c.name成为NULL

考虑使用左连接,因为它们通常更自然地编写。无论如何,将该条件应用于join子句而不是where子句,以避免将其转换为内连接。

借用并修改@ dasblinkenlight的查询:

SELECT DISTINCT
    a.zcta5ce10 AS zipcode
,   c.report_year
,   c.aal 
FROM  us_zip a
LEFT OUTER JOIN aal_county_zip c
      ON c.zip = a.zcta5ce10
     AND c.report_year=2009 
     AND LOWER(c.name) = LOWER('alachua') 
ORDER BY c.report_year DESC

那应该修复你的“只返回两行”的问题。也就是说,查询可能在us_zip上缺少一些额外的标准(和排序标准)。

答案 1 :(得分:0)

SELECT DISTINCT a.zcta5ce10 AS zipcode, 
                c.report_year, 
                c.aal 
FROM   aal_county_zip c 
       RIGHT OUTER JOIN us_zip a 
                     ON ( c.zip = a.zcta5ce10 ) 
WHERE  Lower(c.name) = Lower('alachua') 
  AND  COALESCE(c.report_year, 2009)=2009
ORDER  BY c.report_year DESC 

SELECT DISTINCT a.zcta5ce10 AS zipcode, 
                c.report_year, 
                c.aal 
FROM   aal_county_zip c 
       RIGHT OUTER JOIN us_zip a 
                     ON ( c.zip = a.zcta5ce10 AND c.report_year=2009) 
WHERE  Lower(c.name) = Lower('alachua') 
ORDER  BY c.report_year DESC 

您正在执行RIGHT OUTER JOIN,因此您的第一个表aal_county_zip可能包含空值。因此,要么使用COALESCE来计算这些空值,要么将其作为连接条件的一部分。