【问题标题】:SQL query - IS NULLSQL 查询 - 为空
【发布时间】:2013-11-11 20:33:12
【问题描述】:

表格:

国家 -------- PK CountryID 姓名 城市 -------- PK CityID FK CountryID 姓名 飞机场 -------- PK机场ID FK CityID 姓名

我的任务是选择没有机场的国家/地区的名称。

我可以想象只有一种解决方案,除了(或减号)

SELECT Country.Name 
FROM Country EXCEPT (SELECT DISTINCT Country.Name FROM Country, City, Airport 
WHERE City.CountryID = Country.CountryID AND Airport.CityID = City.CityID); 

但是是否可以不使用 EXCEPT 而使用 IS NULL 之类的东西?

【问题讨论】:

  • 当然.. 带有空检查的外连接应该可以工作。

标签: sql


【解决方案1】:
SELECT cn.CountryID 
  FROM Country cn
  LEFT JOIN City ct ON cn.CountryID = ct.CountryID
  LEFT JOIN Airport ar on ar.CityID=ct.CityID
 WHERE ar.AirportID is null

【讨论】:

  • 我认为这个查询还会返回存在机场的国家,但也存在没有机场的城市。
  • 感谢 Valex,感谢您指出我的错误。为您的正确答案 +1。
【解决方案2】:

如果您需要使用IS NULL 进行此查询,请尝试以下查询:

SQLFiddle demo

select ct.CountryId,max(ct.Name) from Country ct
left join City c on ct.CountryId=c.CountryId
left join Airport a on a.CityId=c.CityID
group by ct.CountryId
HAVING max(a.AirportID) IS NULL

【讨论】:

    【解决方案3】:

    你可以使用它,但它基本上是相同的东西,但语法不同。

    SELECT Country.Name 
    FROM Country 
    Where Country.Name Not IN 
        (
            SELECT DISTINCT Country.Name FROM Country, City, Airport 
            WHERE City.CountryID = Country.CountryID AND Airport.CityID = City.CityID
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多