Postgres至少选择'项目

时间:2016-08-01 19:43:58

标签: postgresql

我想选择要发布的评论,老年人然后特别评论,但我想在结果中至少 5条评论。

因此,如果sql:SELECT * FROM comments WHERE id >= :comment_id的评论少于5条,我必须另外选择SELECT * FROM comments LIMIT 5

是否可以在一个请求中获得相同的逻辑?

2 个答案:

答案 0 :(得分:1)

with c as (
    select count(*) as c
    from comments
    where id >= :comment_id
)
select *
from comments
where id >= :comment_id
union all
(
    select *
    from comments
    where id < :comment_id
    order by id desc
    limit greatest(5 - (select c from c), 0)
)
;

答案 1 :(得分:0)

尝试:

WITH x AS {
  SELECT * FROM comments WHERE id >= :comment_id
),
y AS (
  SELECT * FROM comments
  LIMIT 5
)
SELECT * FROM x
WHERE 5 <= ( SELECT count(*) FROM x )
UNION ALL
SELECT * FROM y
WHERE 5 > ( SELECT count(*) FROM x )