mysql - 在 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 子句中单独评估一个变量对我来说有点奇怪。)
想法?
解决方案
见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 |
+---------------+
推荐阅读
- jquery - 如何检查 sharepoint 中 if 语句的一组单选按钮值?
- scala - 针对 Any => List[Any] => List[Long] 的模式匹配
- c++ - ipiv magma_getrs_gpu 上的双重释放或损坏(输出)
- django - 向视图中的表单添加数据,显示在模板中
- c# - Sprite 未设置且 Animator 出现故障
- javascript - 上传到服务器以进行电子生成器自动更新所需的工件列表?
- xpath - 如何使用 XPath 从 div 类中获取 href 锚文本
- mongodb - 匹配当前文档中的数组
- java - 如何为许多具体类型创建抽象工厂
- python-3.x - 使用 for 循环将列添加到 pandas 数据框