如何编写 SQL 语句来查找不关联的记录?
我有两个表,如下所示:
tblCountry (countryID, countryCode)
tblProjectCountry(ProjectID, countryID)
tblCountry
表是所有国家/地区及其代码的列表,tblProjectCountry
表将某些国家/地区与某些项目相关联。我需要一个 SQL 语句,为我提供一个国家/地区列表及其国家/地区代码,这些国家/地区代码在 tblProjectCountry
表中没有关联记录。到目前为止,我到达这里:
SELECT tblCountry.countryID, tblCountry.countryCode
FROM tblProjectCountry INNER JOIN
tblCountry ON tblProjectCountry.countryID = tblCountry.countryID
WHERE (SELECT COUNT(ProjectID)
FROM tblProjectCountry
WHERE (ProjectID = 1) AND (countryID = tblCountry.countryID)) = 0
上面的语句解析为正确的,但没有给出我正在寻找的确切结果。有人可以帮忙吗?
I have two tables as follows:
tblCountry (countryID, countryCode)
tblProjectCountry(ProjectID, countryID)
The tblCountry
table is a list of all countries with their codes and the tblProjectCountry
table associates certain countries with certain projects. I need an SQL statement that gives me a list of the countries with their country code that do NOT have an associated record in the tblProjectCountry
table. so far I got to here:
SELECT tblCountry.countryID, tblCountry.countryCode
FROM tblProjectCountry INNER JOIN
tblCountry ON tblProjectCountry.countryID = tblCountry.countryID
WHERE (SELECT COUNT(ProjectID)
FROM tblProjectCountry
WHERE (ProjectID = 1) AND (countryID = tblCountry.countryID)) = 0
The above statement parses as correct but doesn't give the exact result I'm looking for. Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这有效吗?
Does this work?
另一种选择:
这使用所谓的 相关子查询
请注意,我还使用 EXISTS 关键字 (另请参阅)
在 SQL Server 上,NOT EXISTS 通常是 被认为性能更高。在其他 RDMS 的 您的里程可能会有所不同。
Another alternative:
This uses what's called a correlated subquery
Note that I also make use of the EXISTS keyword (see also)
On SQL Server, NOT EXISTS is generally thought to be more performant. On other RDMS's your mileage may vary.
至少有两种方法可以查找不关联的记录。
1. 使用
LEFT JOIN
正如erikkallen提到的,这可能表现不佳。
2. 使用
NOT EXISTS
rohancragg 和其他:
取决于您的 DBMS 以及国家和项目表的大小,两个版本都可以表现更好。
在我对 MS SQL 2005 的测试中,对包含约 250 个国家/地区和约 5000 个项目的表的第一个和第二个查询之间没有显着差异。然而,在超过 300 万个项目的表上,第二个版本(使用
NOT EXISTS
)的表现要好得多。因此,像往常一样,值得检查这两个版本。
There are, at least, two ways to find unassociated records.
1. Using
LEFT JOIN
As erikkallen mentioned this could perform not well.
2. Using
NOT EXISTS
Various version of using
NOT EXISTS
orIN
were suggested by rohancragg and others:Depends on your DBMS and size of countries and projects tables both version could perform better.
In my test on MS SQL 2005 there was no significant difference between first and second query for table with ~250 countries and ~5000 projects. However on table with over 3M projects second version (using
NOT EXISTS
) performed much, much better.So like always, it's worth to check both versions.
选择... ID 不在的地方(选择...)
SELECT ... WHERE ID NOT IN (SELECT ... )