← 中文资源

简体中文版本

用 IS DISTINCT FROM 做空值安全比较

用 IS DISTINCT FROM 替代不等号比较两个可空列,避免空值导致行被静默过滤。

阅读英文原文

实现说明

实际执行的是 SELECT——涉及的对象是 user_migrations、current_email。 机制上由这些部分组成:WHERE 按条件筛出这条语句真正触碰的行;ORDER BY 固定了输出顺序;DISTINCT 折叠重复行。

常见问题

这里用到哪些关系?

引用的是 user_migrations、current_email。

核心语句

SELECT
    id,
    legacy_email,
    current_email
FROM user_migrations
WHERE legacy_email IS DISTINCT FROM current_email
  AND resolved_at IS NULL
ORDER BY id;

代码示例

SELECT
    id,
    legacy_email,
    current_email
FROM user_migrations
WHERE legacy_email IS DISTINCT FROM current_email
  AND resolved_at IS NULL
ORDER BY id;

-- Using legacy_email <> current_email instead would silently exclude every
-- row where either side is NULL, which is exactly the mismatch we want.