首页 > 解决方案 > 在 mysql 语句的 where 子句中使用可能为空的动态变量

问题描述

我在 mysql 变量中选择一个值。例如...

select          @userId := userId
from            myTable 
where           id = ?;

@userId 的值可能为空。

现在我想根据@userId 的值更新另一个表中的行。

简单地声明“where userId = @userId”并不总是有效,因为“userId = null”在 mysql 中永远不会返回 true,即使 userId 为 null。

以下语句似乎可以正常工作...

update          myOtherTable
set             something = "something"
where           (
                    userId = @userId or 
                    (@userId is null and userId is null)
                );

...但是我只是想在这里由大师来运行它,以确保它基本上是“好的”。(在 where 子句中单独评估一个变量对我来说有点奇怪。)

想法?

标签: mysqldynamic-sql

解决方案


https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_equal-to

<=>

NULL 安全相等。此运算符执行与 = 运算符类似的相等比较,但如果两个操作数都为 NULL,则返回 1 而不是 NULL,如果一个操作数为 NULL,则返回 0 而不是 NULL。

mysql> select null <=> 1;
+------------+
| null <=> 1 |
+------------+
|          0 |
+------------+
1 row in set (0.00 sec)

mysql> select null <=> null;
+---------------+
| null <=> null |
+---------------+
|             1 |
+---------------+

推荐阅读