0

这是 SQL,“aal_county_zip”有 2 个邮政编码的条目,而“us_zip”有 15 个邮政编码。要求是获得 15 行,其中只有 2 行具有来自“aal_county_zip”的数据。它的工作方式与普通连接一样。如何更改 SQL/表结构以使其正常工作。我还想添加下面评论的条件。

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 
4

2 回答 2

1

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

考虑改用左连接,因为它们通常更自然地编写。在任何情况下,将该条件应用于 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

于 2014-01-17T11:01:53.790 回答
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,要么将其作为连接条件的一部分。

于 2014-01-17T10:24:59.323 回答