SQL AND、OR 和 NOT 运算符

SQL 中的 ANDORNOT 运算符与 WHEREHAVING 子句一起使用。


SQL AND 运算符

SQL AND 运算符在所有条件都为 TRUE 时选择数据。例如:

-- select the first_name and last_name of all customers
-- who live in 'USA' and have the last name 'Doe'

SELECT first_name, last_name
FROM Customers
WHERE country = 'USA' AND last_name = 'Doe';

在这里,SQL 命令从 Customers 表中选择所有 countryUSAlast_nameDoe 的客户的 first_namelast_name

How to use the AND operator in SQL?
示例:SQL AND 运算符

SQL OR 运算符

SQL OR 运算符在任何一个条件为 TRUE 时选择数据。例如:

-- select first and last name of customers
-- who either live in the USA
-- or have the last name 'Doe'

SELECT first_name, last_name
FROM Customers
WHERE country = 'USA' OR last_name = 'Doe';

在这里,SQL 命令从 Customers 表中选择所有 countryUSAlast_nameDoe 的客户的 first_namelast_name

How to use the OR operator in SQL?
示例:SQL OR 运算符

SQL NOT 运算符

SQL NOT 运算符在给定条件为 FALSE 时选择数据。例如:

-- select customers who don't live in the USA

SELECT first_name, last_name
FROM Customers
WHERE NOT country = 'USA';

在这里,SQL 命令从 Customers 表中选择所有 country 不为 USA 的客户的 first_namelast_name

How to use the NOT operator in SQL?
示例:SQL NOT 运算符

组合多个运算符

也可以在一个 SQL 语句中组合多个 ANDORNOT 运算符。

例如,假设我们想选择 countryUSAUK,并且 age 小于 26 的客户。

-- select customers who live in either USA or UK and whose age is less than 26

SELECT *
FROM Customers
WHERE (country = 'USA' OR country = 'UK') AND age < 26;
How to use AND and OR operators together in SQL?
示例:SQL AND 和 OR 运算符

示例:在 SQL 中组合多个运算符

让我们看另一个组合运算符的例子。

-- exclude customers who are from the USA and have 'Doe' as their last name

SELECT *
FROM customers
WHERE NOT country = 'USA' AND NOT last_name = 'Doe';

在这里,SQL 命令从 Customers 表中选择所有 country 不为 USAlast_name 不为 Doe 的客户。

How to use AND and NOT operators together in SQL?
示例:SQL AND 和 NOT 运算符

另请阅读

在结束之前,让我们测试一下你对 SQL AND、OR 和 NOT 运算符的知识!你能解决下面的挑战吗?

挑战

编写一个 SQL 查询来查找 2023 年 3 月下达的所有订单。

假设你有一个名为 Orders 的表。此表的架构如下:

Orders

列名

数据类型

order_id

int

order_date

日期

customer_id

int

一家公司维护着一个订单数据库,每条记录都详细说明了订单下达的时间和下达订单的客户。


你的任务是编写一个 SQL 查询来查找 2023 年 3 月下达的所有订单。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战