2014-02-19 120 views
0

我正在學習SQL,這裏是一個查詢,我只是跑(從W3學校):爲什麼SQL允許這種奇怪的IN子句使用?

SELECT * FROM Products 
WHERE (Price BETWEEN 10 AND 20) 
AND NOT (CategoryID in (2 OR 3)) 

類別ID是一個數列,以及正確的使用方法應該是:

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? */ 

源 - http://www.w3schools.com/sql/sql_between.asp

+0

[不要使用w3schools - 查看鏈接爲什麼](http://www.w3fools.com) –

+0

@marc_s - 好的,謝謝 – Coffee

+1

我的數據庫(postgresql 9.3)不允許它。你用什麼數據庫?錯誤:OR的參數必須是布爾類型,而不是整型 –

回答

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子句中拉了回來只有兩個BusinessEntityIDs:

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);

相關問題