具有多个条件的 PostgreSQL select 记录

PostgreSQL select record with multiple condition

我正在尝试 select 记录,但没有得到我想要的记录。这是我的 sqlfiddle http://sqlfiddle.com/#!17/5296a/1

所以当我select使用下面的查询

记录时
select title from post where (id>3 and author_id=3) or id>3 limit 1

它给了我标题为 DDDDD 的结果。它应该给我 GGGGGGGG.

我想检查是否有 author_id=3 且大于 post id=3 的记录,如果没有,则获取任何 post id 大于 3 的记录.

我不确定我在这里遗漏了什么。

I wanted to check if there is any record with author_id=3 and greater than the post id=3 if not then just get the any post id greater than 3.

根据您的描述,您想要:

select title
from post 
where id > 3
order by (author_id = 3) desc
limit 1;

Here 是一个 db<>fiddle。这将过滤所有行,因此只有 id > 3order by 将任何带有 author_id = 3 的行放在第一位,因此 limit 会 return 那一个。

您的版本只是 return 匹配 where 条件的任意行 -- 并且该条件等同于 where id > 3where 条件不提供任何类型的“偏好”。它们只是指定给定行是否在结果集中。