我想以三种排序顺序之一返回我的帖子行,由sorting_param
函数参数控制。排序很复杂,不适合简单的排序ORDER BY CASE ...
。所以我正在考虑将每个排序写入其自己的 CTE,然后选择其中一个 CTE 作为最终输出。但是,我不希望 PostgreSQL 浪费时间在这三个上,只浪费我选择的那个。那么这三个都会实现还是只有我选的那个会实现?或者有更好的方法吗?PostgreSQL 版本 16。简化代码如下。
WITH posts_by_order1 AS
(
SELECT p.id
FROM post p
ORDER BY [some complex ordering 1]
LIMIT 10
),
posts_by_order2 AS
(
SELECT p.id
FROM post p
ORDER BY [some complex ordering 2]
LIMIT 10
),
posts_by_order3 AS
(
SELECT p.id
FROM post p
ORDER BY [some complex ordering 3]
LIMIT 10
)
SELECT * FROM posts_by_order1 WHERE sorting_param = 0
UNION ALL
SELECT * FROM posts_by_order2 WHERE sorting_param = 1
UNION ALL
SELECT * FROM posts_by_order3 WHERE sorting_param = 2;
不幸的是我不能这样做:
ORDER BY
CASE
WHEN sorting_param = 0 THEN p.date
WHEN sorting_param = 1 THEN p.name
ELSE NULL
END DESC, ...