SQL 中的 AND
、OR
和 NOT
运算符与 WHERE
或 HAVING
子句一起使用。
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 表中选择所有 country 为 USA 且 last_name 为 Doe 的客户的 first_name 和 last_name。

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 表中选择所有 country 为 USA 或 last_name 为 Doe 的客户的 first_name 和 last_name。

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_name 和 last_name。

组合多个运算符
也可以在一个 SQL 语句中组合多个 AND
、OR
和 NOT
运算符。
例如,假设我们想选择 country 是 USA 或 UK,并且 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;

示例:在 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 不为 USA 且 last_name 不为 Doe 的客户。

另请阅读