Postgresql 并与空字段进行比较

发布于 2024-10-01 08:58:00 字数 642 浏览 2 评论 0原文

似乎在 PostgreSQL 中,empty_field != 1(或其他值)是FALSE。如果这是真的,有人可以告诉我如何与空字段进行比较吗?

我有以下查询,它翻译为“选择用户组中尚未投票的所有帖子:

SELECT p.id, p.body, p.author_id, p.created_at
FROM posts p
LEFT OUTER JOIN votes v ON v.post_id = p.id
WHERE p.group_id = 1 
AND v.user_id != 1

并且它不输出任何内容,即使 votes 表为空。也许我的有问题查询而不是上面的逻辑?

编辑: 似乎将 v.user_id != 1 更改为 v.user_id IS DISTINCT FROM 1 ,完成了工作。 来自 PostgreSQL 文档:

对于非空输入,与 与 <> 相同操作员。 然而,当两个输入都为空时 将返回 false,并且当只有一个时 输入为 null 则返回 true。

It seems that in PostgreSQL, empty_field != 1 (or some other value) is FALSE. If this is true, can somebody tell me how to compare with empty fields?

I have following query, which translates to "select all posts in users group for which one hasn't voted yet:

SELECT p.id, p.body, p.author_id, p.created_at
FROM posts p
LEFT OUTER JOIN votes v ON v.post_id = p.id
WHERE p.group_id = 1 
AND v.user_id != 1

and it outputs nothing, even though votes table is empty. Maybe there is something wrong with my query and not with the logic above?

Edit: it seems that changing v.user_id != 1, to v.user_id IS DISTINCT FROM 1, did the job.
From PostgreSQL docs:

For non-null inputs, IS DISTINCT FROM
is the same as the <> operator.
However, when both inputs are null it
will return false, and when just one
input is null it will return true.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

昨迟人 2024-10-08 08:58:00

如果你想返回 v.user_id 为 NULL 的行,那么你需要特殊处理。修复它的一种方法是编写:

AND COALESCE(v.user_id, 0) != 1

另一种选择是:

AND (v.user_id != 1 OR v.user_id IS NULL)

编辑:spacemonkey 是正确的,在 PostgreSQL 中,您应该在此处使用 IS DISTINCT FROM

If you want to return rows where v.user_id is NULL then you need to handle that specially. One way you can fix it is to write:

AND COALESCE(v.user_id, 0) != 1

Another option is:

AND (v.user_id != 1 OR v.user_id IS NULL)

Edit: spacemonkey is correct that in PostgreSQL you should use IS DISTINCT FROM here.

栖竹 2024-10-08 08:58:00

NULL 是一个未知值,因此它永远不能等于某个值。研究使用 COALESCE 函数。

NULL is a unknown value so it can never equal something. Look into using the COALESCE function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文