【发布时间】:2021-09-26 17:02:33
【问题描述】:
我正在尝试组合一个 SQL 查询,该查询将基于简单的WHERE 条件返回数据,但如果条件不满足,也会返回第一个可用记录。
| author_id | post_id | publish_date |
|---|---|---|
| 1 | 31 | 2021-07-23 |
| 2 | 432 | 2021-06-22 |
| 2 | 555 | 2020-07-23 |
使用我的基本查询上面的数据看起来像这样
select *
from posts
where author_id = 1
and publish_date > '2021-07-01'
order by publish_date
结果,即作者在指定日期后发表的帖子
| author_id | post_id | publish_date |
|---|---|---|
| 1 | 31 | 2021-07-23 |
由于作者 2 在此日期之后没有帖子,我希望它返回指定作者的最新帖子。 我希望能够输出“作者>自search_date>以来没有发布,最近的帖子是在publish_date> " 无需多次查询数据库。
author_id 2 的期望结果(没有任何发布日期 > '2021-07-01' 的帖子)
| author_id | post_id | publish_date |
|---|---|---|
| 2 | 432 | 2021-06-22 |
如果单条语句不满足日期条件,是否可以查询第一条可用记录?
【问题讨论】:
-
您需要将这两条记录作为两行(具有相同的列)吗?
标签: sql postgresql