SQL IN 和 NOT IN 运算符

我们使用 IN **运算符**与 WHERE 子句一起在列表中匹配值。

示例

-- select customers from the USA

SELECT first_name, country
FROM Customers
WHERE country IN ('USA');

这里,SQL 命令从 Customers 表中选择 country 值为 'USA' 的行。


SQL IN 语法

SELECT column1, column2, ...  
FROM table
WHERE column IN (value1, value2, ...);

这里,

  • column1, column2, ... 是表列。
  • table 是我们从中选择数据的表名。
  • column 是值进行比较的列。
  • IN 运算符指定 column 值应与之比较的值。
  • value1, value2, ...column 值与之比较的值。

示例:SQL IN

-- select rows if the country is either USA or UK

SELECT first_name, country
FROM Customers
WHERE country IN ('USA', 'UK');

这里,SQL 命令在 country 是 **USA** 或 **UK** 时选择行。

How to use IN operator in SQL
示例:SQL IN 运算符

示例:IN 运算符根据国家/地区值选择行

IN 运算符可用于选择特定值存在于指定字段中的行。

-- select rows with value 'USA' in the country column

SELECT first_name, country
FROM Customers
WHERE 'USA' IN (country);

这里,SQL 命令在 country 字段中存在 USA 值时选择行。

How to use IN operator with Value in SQL
示例:带值的 SQL IN 运算符

SQL NOT IN 运算符

NOT IN 运算符排除列表中匹配值的行。它返回除了被排除的行之外的所有行。

-- select rows where country is not in UK or UAE

SELECT first_name, country
FROM Customers
WHERE country NOT IN ('UK', 'UAE');

这里,SQL 命令在 country 列中不存在 **UK** 或 **UAE** 时选择行。

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

注意: NOT 运算符反转了 IN 运算符的工作方式。它们基本上是两个组合的运算符。要了解更多信息,请访问 SQL AND、OR 和 NOT 运算符


更多关于 SQL IN

带重复值的 SQL IN 运算符

IN 运算符忽略列表中的重复值。例如,

-- IN ignores the duplicate 'USA' value

SELECT first_name, country
FROM Customers
WHERE country IN ('USA', 'UK', 'USA');

上面的代码等同于下面的代码。

-- select customers that live in either the USA or the UK

SELECT first_name, country
FROM Customers
WHERE country IN ('USA', 'UK');
带子查询的 SQL IN 运算符

假设我们只想获取那些已下订单的客户的详细信息。

以下是使用子查询实现此目的的方法。

-- select only those customers who have placed an order
-- the subquery is enclosed within parentheses after the IN keyword

SELECT customer_id, first_name
FROM Customers 
WHERE customer_id IN (
  SELECT customer_id
  FROM Orders
);

这里,SQL 命令

  1. 使用子查询从 Orders 表中选择 customer_id
  2. Customers 表中选择 customer_id 存在于子查询结果集中的行,即如果 customer_id 也存在于 Orders 表中。

要了解更多信息,请访问 SQL 子查询


另请阅读

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

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

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

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