SQL 运算符

运算符是用于对值执行操作的符号(和关键字)。

这些运算符与 SQL 子句一起使用,例如:SELECTWHEREON 等。

SQL 中的运算符可以分为:

  • 算术运算符
  • 比较运算符
  • 逻辑运算符

SQL 算术运算符

算术运算符执行简单的算术运算,例如加法、减法、乘法等。

运算符 描述
+ 加法
- 减法
* 乘法
/ 除法
% 模数(余数)

加法运算符

-- returns new column named total_amount which is 
-- 100 added to the amount field
SELECT item, amount, amount+100 AS total_amount
FROM Orders;

减法运算符

-- returns new column named offer_price which is 
-- 20 subtracted to the amount field
SELECT item, amount, amount-20 AS offer_price
FROM Orders;

乘法运算符

-- returns new column named total_amount  which is 
-- 4 multiplied to the amount field
SELECT item, amount, amount*4 AS total_amount
FROM Orders;

除法运算符

-- returns new column named half_amount which is 
-- divided by 2 to the amount field
SELECT item, amount, amount/2 AS half_amount
FROM Orders;

模数(余数)运算符

-- returns 1 which is remainder
SELECT 10 % 3 AS result;

比较运算符

我们可以使用 SQL 中的比较运算符来比较两个值。这些运算符返回 1(表示真)或 0(表示假)。

运算符 描述
= 等于
< 小于
> 大于
<= 小于或等于
>= 大于或等于
<>, != 不等于

等于运算符

-- returns records where customer_id is only 4
SELECT order_id, item, amount
FROM Orders
WHERE customer_id = 4;

小于运算符

-- returns records where amount is less than 400 (exclusive)
SELECT order_id, item, amount
FROM Orders
WHERE amount < 400;

大于运算符

-- returns records where amount is greater than 400 (exclusive)
SELECT order_id, item, amount
FROM Orders
WHERE amount > 400;

小于或等于运算符

-- returns records where amount is less than or equal to 400
SELECT order_id, item, amount
FROM Orders
WHERE amount <= 400;

大于或等于运算符

-- returns records where amount is greater than or equal to 400
SELECT order_id, item, amount
FROM Orders
WHERE amount >= 400;

不等于运算符

-- returns records where amount is not equal to 400
SELECT order_id, item, amount
FROM Orders
WHERE amount != 400;

除了 !=,我们还可以使用 <> 符号表示不等于操作。


逻辑运算符

我们可以使用逻辑运算符来比较多个 SQL 命令。这些运算符返回 1(表示真)或 0(表示假)。

SQL 中可用的逻辑运算符有:

在结束之前,让我们测试一下你对 SQL 运算符的了解!你能解决下面的挑战吗?

挑战

编写一个 SQL 查询来计算产品数量。

假设您有一个名为 **Products** 的表。该表的架构如下

产品 (Products)

列名

数据类型

id

int

name

varchar(100)

price

int

quantity

int

商店在此表中维护产品记录。每个产品都有价格和指定的库存数量。


你的任务是编写一个 SQL 查询,计算价格低于 200 的产品数量。该查询还应包括不考虑价格中任何 NULL 值的总产品数量。

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

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

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

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