返回ID NOT某些表中的结果

时间:2012-03-05 19:57:43

标签: sql sql-server sql-server-2008 tsql

我正在尝试写一个写,而我正在寻找的逻辑基本上就是这样。如果表1中不存在表1中的任何用户ID,则显示结果中的用户ID。所以我做了:

SELECT
  UserColder.ContactName,
  UserColder.Phone,
  UserColder.Email,
  UserColder.Website,
  Country.Name,
  UserColderZIP.[ZIP Code],
  UserColderZIP.[State Abbreviation]
FROM
  dbo.UserColder
  LEFT OUTER JOIN dbo.CountryUser
    ON UserColder.ID = CountryUser.[User ID]
  INNER JOIN dbo.Country
    ON CountryUser.[Foreign ID] = Country.ID
  LEFT OUTER JOIN dbo.UserColderZIP
    ON UserColder.ID = UserColderZIP.UserColder
WHERE
  UserColder.ID NOT IN (CountryUser.[User ID])

它返回没有Where的数据但是使用Where我试图让它显示所有结果,其中来自UserColder的Id在CountryUser中没有任何记录。现在它没有返回任何结果,我知道那里不存在ID 2。知道我做错了吗?

谢谢!

2 个答案:

答案 0 :(得分:4)

由于您拥有LEFT OUTER JOIN,要从UserColder获取CountryUser中不存在的记录,请检查NULL。没有相应值的连接行将返回NULL

WHERE
  CountryUser.[User ID] IS NULL

答案 1 :(得分:0)

只需从UserColder获取信息,并确保UserColder.ID不在CountryUser中,方法是检查它(select语句在哪里)。

SELECT
  UserColder.ContactName,
  UserColder.Phone,
  UserColder.Email,
  UserColder.Website,
  Country.Name,
  UserColderZIP.[ZIP Code],
  UserColderZIP.[State Abbreviation]
FROM
  dbo.UserColder
  INNER JOIN dbo.Country
    ON CountryUser.[Foreign ID] = Country.ID
  LEFT OUTER JOIN dbo.UserColderZIP
    ON UserColder.ID = UserColderZIP.UserColder
WHERE
  UserColder.ID NOT EXISTS (select [user id] from dbo.CountryUser where CountryUser.[User ID])