在一个 table 上的简单 select 查询中获取消息 8623,级别 16,状态 1,第 1 行错误

Getting Msg 8623, Level 16, State 1, Line 1 error on a simple select query on one table

如何优化在一个 table 上搜索不属于某个集合的 ID 的简单查询。

我创建了以下查询

Select userId 
from user 
where userId not in (5000, 5001, 5002, 5003, more....)

请注意,该列表包括 35000 多行。我收到以下数据库错误

Msg 8623, Level 16, State 1, Line 1
The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions.

有些人建议使用左连接优化查询,但我只搜索一个 table 那么有什么替代方法?

这是一个documented behavior:

Explicitly including an extremely large number of values (many thousands of values separated by commas) within the parentheses, in an IN clause can consume resources and return errors 8623 or 8632. To work around this problem, store the items in the IN list in a table, and use a SELECT subquery within an IN clause.

35000 显然符合 数千。因此,根据文档,您应该创建一个 table(或临时 table)来存储您的值,然后 left join 如下所示:

select u.userId 
from user u
left join mytemptable t on t.userId = u.userId
where t.userId  is null

您也可以使用 not exists:

select u.userId
from user u
where not exists (select 1 from mytemptable t where t.userId = u.userId)

作为奖励,请注意使用上述技术之一修复了原始查询的空安全问题(实际上,如果 IN 列表中的任何值是 NULL,无论 userId) 的值如何,NOT IN 条件都将被视为满足。