SQL AND 和 OR

SQL AND/OR 操作符用来在SQL WHERE子句中对两个或以上的判断条件作与/或操作。它们可以用于 SELECT, UPDATE, DELETE 或 INSERT 语句。

AND 操作符:在WHERE子句中当所有条件都为真时将执行查询;OR 操作符:在WHERE子句中当任一条件为真时将执行查询。

语法

SELECT columns
FROM 数据表
WHERE condition1
     {[AND|OR] condition2}+

{}+ 表示可以重复一或多次。

注:我们可以用园括号()来指定执行判定条件的顺序。

范例

数据表: Employees

EmployeeId FirstName LastName Department Salary
203 Mazojys Fxoj Finance 78000
204 Jozzh Lnanyo Finance 45800
205 Syllauu Dfaafk Finance 57000
206 Gecrrcc Srlkrt Finance 62000
302 Jssme Bdnaa Development 75000
303 Dnnaao Errllov Development 55000
304 Tyoysww Osk Development 49000

例1
我们想选择Firstname是Syllauu,而且Lastname是Dfaafk的职员:

SELECT *
FROM Employees
WHERE FirstName='Syllauu' AND LastName='Dfaafk'

结果会类似于:

EmployeeId FirstName LastName Department Salary
205 Syllauu Dfaafk Finance 57000

例2
我们想选择LastName是Lnanyo 或者Bdnaa的职员:

SELECT *
FROM Employees
WHERE LastName='Lnanyo' OR LastName='Bdnaa'

结果会类似于:

EmployeeId FirstName LastName Department Salary
204 Jozzh Lnanyo Finance 45800
302 Jssme Bdnaa Development 75000

例3
现在我么加入更多的条件:

SELECT *
FROM Employees
WHERE Department='Finance' AND (LastName='Lnanyo' OR LastName='Bdnaa')

结果会类似于:

EmployeeId FirstName LastName Department Salary
204 Jozzh Lnanyo Finance 45800