Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MySQL 比较运算符 #74

Open
techiall opened this issue Aug 15, 2020 · 0 comments
Open

MySQL 比较运算符 #74

techiall opened this issue Aug 15, 2020 · 0 comments
Labels

Comments

@techiall
Copy link
Owner

MySQL 运算符

运算符 描述 备注
> / >= 大于 / 大于等于
< / <= 小于 / 小于等于
<> / != 不等于 两者都是不等于,和 <=> 运算符有区别
<=> NULL-safe 等于运算符 这个在有些场景下特别有用
= 等于

MySQL 比较

在 MySQL 中,NULL 和 NULL 是没法做比较的,也就是 NULL = NULL 的返回值是 NULL。

MariaDB [mybatis]> SELECT NULL = NULL;
+-------------+
| NULL = NULL |
+-------------+
|        NULL |
+-------------+

MariaDB [mybatis]> SELECT NULL != NULL;
+--------------+
| NULL != NULL |
+--------------+
|         NULL |
+--------------+

> / >= / < / <= / = / != / <> 都是如上同理。要判断是不是 NULL,可以使用 IS NULL / IS NOT NULL 进行判断。

MariaDB [mybatis]> SELECT NULL IS NULL;
+--------------+
| NULL IS NULL |
+--------------+
|            1 |
+--------------+

MariaDB [mybatis]> SELECT NULL IS NOT NULL;
+------------------+
| NULL IS NOT NULL |
+------------------+
|                0 |
+------------------+

这样子的结果是对的,但是还存在一种情况,我们不知道要比较的值是不是 NULL,这时候就需要 <=>

MariaDB [mybatis]> SELECT NULL <=> NULL;
+---------------+
| NULL <=> NULL |
+---------------+
|             1 |
+---------------+


MariaDB [mybatis]> SELECT 1 <=> NULL;
+------------+
| 1 <=> NULL |
+------------+
|          0 |
+------------+


MariaDB [mybatis]> SELECT !(1 <=> NULL);
+---------------+
| !(1 <=> NULL) |
+---------------+
|             1 |
+---------------+


MariaDB [mybatis]> SELECT !(NULL <=> NULL);
+------------------+
| !(NULL <=> NULL) |
+------------------+
|                0 |
+------------------+

有时候需要在 WHERE 里面写 name = ${name} AND type = 1,你想要查询 name 这个字段为 NULL 的记录并且 type 等于 1,但是发现不管怎么查询都是 Empty set。

如果换成 name <=> ${name} AND type = 1

这样子 name 的值传入 NULL,也可以查询,也就是查询 name 为 NULL(相当于 name IS NULL) 并且 type 等于 1 的记录。

name 传入的值非 NULL,例如 AAA,也就会查询 name 等于 AAA 并且 type 等于 1 的记录。

当然了,你也可以在程序里面判断 name 是不是 NULL,如果是 NULL 的话使用 name IS NULL AND type = 1 进行查询。

不是 NULL,就使用 name = ${name} AND type =1 进行查询。

参考文献

@techiall techiall added the SQL label Aug 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant