外观
比较运算符
比较运算符在查询数据时常用的一种运算符,SELECT语句中经常用到比较运算符。MySQL中常用的比较运算符如下表。
| 符号 | 名称 | 示例 | 符号 | 名称 | 示例 |
|---|---|---|---|---|---|
| = | 等于 | id=5 | is not null | n/a | id is not null |
| > | 大于 | id>5 | between and | n/a | id between 1 and 5 |
| < | 小于 | id<5 | in | n/a | id in (3,4,5) |
| >= | 大于等于 | id>=5 | not in | n/a | id not in (3,4,5) |
| <= | 小于等于 | id<=5 | like | 模式匹配 | name like (‘shi%’) |
| != <> | 不等于 | id!=5 | not like | 模式匹配 | name not like (‘shi%’) |
| is null | n/a | id is null | regexp | 常规表达式 | name 正则表达式 |
下面对常用的比较运算符进行详解。
在进行演示前,我们先创建如下的数据表,并且输入如图的数据。

- 运算符“=”
它用来判断数字、字符串和表达式是否相等。如果相等返回1;否则返回0。如:
select * from tb_demo where id = 1;
- 运算符“<>”和“!=”
这两个不等于符号可以用来判断数字、字符串和表达式等是否不相等,如果不相等则返回1;否则返回0。如:
select * from tb_demo where id != 1;
- 运算符“>”
大于号可以用来判断左边的操作数是否大于右边的操作数。如:
select * from tb_demo where id > 2;
“<”、“>=”、“<=”等的用法与“>”基本相同,这里不再赘述。
- 运算符 IS NULL
IS NULL用于判断操作是否是空值,操作数为空值时结果返回1,否则返回0。如:
select * from tb_demo where username is NULL;- 运算符 BETWEEN AND
BETWEEN AND运算符用于判断数据是否在某个取值范围内,表达式如下:
x BETWEEN x1 AND x2若x大于x1小于x2则返回1,否则返回0。如:
select * from tb_demo where id between 1 and 3;
- 运算符IN
IN用于判断数据是否存在于某个集合中,表达式如下:
x IN (x1,x2,...,xn)若x的值等于序列中的任意一个则返回1,否则返回0。如
select * from tb_demo where username in ('ab','abc','abcd');
- 运算符 LIKE
LIKE可用于匹配字符串,表达式如下:
x LIKE s若x与s匹配则返回1,否则返回0。如:
select * from tb_demo where password like '%bcde';
- 运算符REGEXP
REGEXP同样用于匹配字符串,但其使用的是正则表达式,表达式如下:
x REGEXP s若x满足s表示的匹配方式则返回1,否则返回0。如:
select * from tb_demo where password regexp '^a';