是否可以在SQL查询的limit子句中使用select count()?
原始查询:
SELECT *
FROM flight_delays
LIMIT 10;
但动态的东西是这样的:
SELECT
*
FROM
flight_delays
LIMIT
(
select
count(foo)
from
bar
group by
bar.bing
)
答案 0 :(得分:1)
您可以这样做:
SELECT fd.*
FROM (SELECT fd.*, ROW_NUMBER() OVER () as seqnum
FROM flight_delays
) fd CROSS JOIN
(select count(foo) as cnt
from bar
) x
WHERE seqnum <= x.cnt;
答案 1 :(得分:1)
您可以创建一个函数,该函数将首先计算LIMIT
的值,然后使用该LIMIT
执行查询。
CREATE OR REPLACE FUNCTION flight_delays_limited()
RETURNS setof flight_delays
$$
DECLARE
limitSize INTEGER = 0;
BEGIN
--custom logic for calculating the limit
select
count(foo) into limitSize
from
bar
group by
bar.bing;
--end custom logic
--return result from select with calculated limit
RETURN QUERY
SELECT * FROM flight_delays
LIMIT limitSize;
end;
$$ language plpgsql;
您可以这样调用该函数:
SELECT * FROM flight_delays_limited();