【发布时间】:2021-08-27 06:20:29
【问题描述】:
我正在尝试使用多列进行键集分页,但除了第一个之外,我无法让它在任何页面上工作。键集列中的一列也可以为空 (col1) 并使用 nulls last 排序。
select colId, col1, col2 from tablename
where (case when parameter_col1 is null then true else col1 < parameter_col1)
and (case when parameter_col2 is null then true else col2 < parameter_col2)
and (case when parameter_colId is null then true else colId < parameter_colId)
order by col1 desc nulls last, col2 desc, colId desc
limit 10;
我在每个where 中使用这些case 语句,以便在结果的第一页上,当null 为所有3 个parameter_ 值传递时,所有内容都会返回。所以它在结果的第一页上运行良好。
但在第二页上,无论parameter_col1 是否为空,它都不会返回正确的结果。使用多列(其中一些可以为空)进行分页的正确方法是什么?
将其分成 2 个单独的查询是否有帮助,一个用于第一页,另一个用于所有后续查询?如果可能的话,我更愿意将它组合到一个查询中以便于维护,但如果不是,我可以将两个查询放入 sql 或 plpgsql 类型的函数中,这样它们至少在同一个地方,并使用if 选择使用哪个。
【问题讨论】:
-
在
WHERE子句中使用AND/OR结构而不是case表达式 通常会更好。 -
你能展示一下它应该是什么样子吗?
-
(parameter_col1 is null OR col1 < parameter_col1) -
我可以用 and/or 重写这种类型的 where 子句吗?
where col = case when param is null then col else param
标签: sql postgresql pagination