我正在学习SQL,这是我刚刚运行的一个查询(来自W3学校):
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT (CategoryID in (2 OR 3 ))
CategoryID是一个数字列,正确的用法应该是:
AND NOT (CategoryID in (2, 3 )) /* give me all rows where categoryID can't be 2 or 3 */
那么你怎么能说:
AND NOT (CategoryID in (2 OR 3 )) /* why does SQL allow it? */
答案 0 :(得分:2)
如果您正在谈论SQL Server,请始终转到源代码。
http://technet.microsoft.com/en-us/library/bb510741.aspx
对于IN运算符:
http://technet.microsoft.com/en-us/library/ms177682.aspx
以下是文档中的示例:
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
这里,IN语句正在查看子查询的结果,即SELECT语句。
让我们更改子查询中的WHERE子句,只返回两个BusinessEntityID:
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
( BusinessEntityID = 2 OR BusinessEntityID = 3 )
);
GO
基本上是
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 (2,3);
GO
这是子查询的WHERE ( BusinessEntityID = 2 OR BusinessEntityID = 3 )
的结果,为什么不允许语法WHERE p.BusinessEntityID IN (2 OR 3);
?