IN (Transact-SQL)
确定指定的值是否与子查询或列表中的值相匹配。
语法
test_expression [ NOT ] IN
( subquery | expression [ ,...n ]
)
参数
test_expression
任何有效的表达式。subquery
包含某列结果集的子查询。 该列必须与 test_expression 具有相同的数据类型。expression[ ,...n ]
一个表达式列表,用来测试是否匹配。 所有的表达式必须与 test_expression 具有相同的类型。
结果类型
Boolean
结果值
如果 test_expression 的值与 subquery 所返回的任何值相等,或与逗号分隔的列表中的任何 expression 相等,则结果值为 TRUE;否则,结果值为 FALSE。
使用 NOT IN 对 subquery 值或 expression 求反。
注意 |
---|
subquery 或 expression 使用 IN 或 NOT IN 与 test_expression 比较后返回的所有空值都将返回 UNKNOWN。 将空值与 IN 或 NOT IN 一起使用会产生意外结果。 |
注释
在 IN 子句中包括数量非常多的值(数以千计)可能会消耗资源并返回错误 8623 或 8632。 若要解决这一问题,请将这些项存储于某个表的 IN 列表中。
错误 8623:
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. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.
错误 8632:
Internal error: An expression services limit has been reached. Please look for potentially complex expressions in your query, and try to simplify them.
示例
A.比较 OR 和 IN
以下示例选择设计工程师、工具设计人员或销售助理等雇员的姓名列表。
USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName, e.JobTitle
FROM Person.Person p
JOIN HumanResources.Employee AS e
ON p.BusinessEntityID = e.BusinessEntityID
WHERE e.JobTitle = 'Design Engineer'
OR e.JobTitle = 'Tool Designer'
OR e.JobTitle = 'Marketing Assistant';
GO
但是,也可以使用 IN 检索相同的结果:
USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName, e.JobTitle
FROM Person.Person p
JOIN HumanResources.Employee AS e
ON p.BusinessEntityID = e.BusinessEntityID
WHERE e.JobTitle IN ('Design Engineer', 'Tool Designer', 'Marketing Assistant');
GO
以下是上面任一查询的结果集。
FirstName LastName Title
--------- --------- ---------------------
Sharon Salavaria Design Engineer
Gail Erickson Design Engineer
Jossef Goldberg Design Engineer
Janice Galvin Tool Designer
Thierry D'Hers Tool Designer
Wanida Benshoof Marketing Assistant
Kevin Brown Marketing Assistant
Mary Dempsey Marketing Assistant
(8 row(s) affected)
B.带子查询使用 IN
以下示例查找 SalesPerson 表中所有销售人员的 ID 以获得当年销售额超过 $250,000 的雇员,然后从 Employee 表中选择 EmployeeID 与 SELECT 子查询的结果相匹配的所有雇员的姓名。
USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName
FROM Person.Person AS p
JOIN Sales.SalesPerson AS sp
ON p.BusinessEntityID = sp.BusinessEntityID
WHERE p.BusinessEntityID IN
(SELECT BusinessEntityID
FROM Sales.SalesPerson
WHERE SalesQuota > 250000);
GO
下面是结果集:
FirstName LastName
--------- --------
Tsvi Reiter
Michael Blythe
Tete Mensa-Annan
(3 row(s) affected)
C.带子查询使用 NOT IN
以下示例查找销售额不超过 $250,000 的销售人员。 NOT IN 查找与值列表中的项不匹配的销售人员。
USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName
FROM Person.Person AS p
JOIN Sales.SalesPerson AS sp
ON p.BusinessEntityID = sp.BusinessEntityID
WHERE p.BusinessEntityID NOT IN
(SELECT BusinessEntityID
FROM Sales.SalesPerson
WHERE SalesQuota > 250000);
GO