POSTGRESQL 限制给定条件的结果查询
POSTGRESQL limit a resulting query given a condition
POSTGRESQL 中有没有一种方法可以在给定条件的情况下限制生成的查询?
我试过这样的事情:
SELECT *
FROM table
LIMIT CASE
WHEN extract(hour from now())=9 then 143
WHEN extract(hour from now())=10 then 178 ETC.`
我需要使用它,因为根据当前时间和 table 中的时间,动态限制条件。
有什么想法或想法吗?
https://www.postgresql.org/docs/current/static/queries-limit.html
LIMIT { number | ALL }
这里不能像ORDER BY
那样使用表达式
https://www.postgresql.org/docs/current/static/queries-order.html
ORDER BY sort_expression1 [ASC | DESC] [NULLS { FIRST | LAST }]
[, sort_expression2 [ASC | DESC] [NULLS { FIRST | LAST }] ...]
这里需要动态 SQL,例如查看 PostgreSQL parameterized Order By / Limit in table function
您可以使用 row_number()
:
SELECT t.*
FROM (SELECT t.*, ROW_NUMBER() OVER (ORDER BY ?) as seqnum
FROM table t
) t
WHERE (extract(hour from now()) = 9 AND seqnum <= 143) OR
(extract(hour from now()) = 10 AND seqnum <= 178) OR
. . .
更可能的解决方案是在应用层处理这个问题。
注意 ?
:这表示用于对数据进行排序的列。通常在使用 LIMIT
时,您需要 ORDER BY
.
POSTGRESQL 中有没有一种方法可以在给定条件的情况下限制生成的查询?
我试过这样的事情:
SELECT *
FROM table
LIMIT CASE
WHEN extract(hour from now())=9 then 143
WHEN extract(hour from now())=10 then 178 ETC.`
我需要使用它,因为根据当前时间和 table 中的时间,动态限制条件。
有什么想法或想法吗?
https://www.postgresql.org/docs/current/static/queries-limit.html
LIMIT { number | ALL }
这里不能像ORDER BY
https://www.postgresql.org/docs/current/static/queries-order.html
ORDER BY sort_expression1 [ASC | DESC] [NULLS { FIRST | LAST }] [, sort_expression2 [ASC | DESC] [NULLS { FIRST | LAST }] ...]
这里需要动态 SQL,例如查看 PostgreSQL parameterized Order By / Limit in table function
您可以使用 row_number()
:
SELECT t.*
FROM (SELECT t.*, ROW_NUMBER() OVER (ORDER BY ?) as seqnum
FROM table t
) t
WHERE (extract(hour from now()) = 9 AND seqnum <= 143) OR
(extract(hour from now()) = 10 AND seqnum <= 178) OR
. . .
更可能的解决方案是在应用层处理这个问题。
注意 ?
:这表示用于对数据进行排序的列。通常在使用 LIMIT
时,您需要 ORDER BY
.