在ResultSet中包含行,但从LIMIT中排除

时间:2019-05-08 18:53:36

标签: postgresql

如何使用SELECT LIMIT行,但从该LIMIT中排除具有disabled = true列值的行。

也应在结果集中返回已禁用的行,但在标识出已禁用的行时不要递增LIMIT

例如: 给定表Runners

id   runner   km_run   disabled
 1     mary      3.5       true
 2     anna      1.5      false
 3     john      6.5      false
 4     bill      1.5      false
 5     jess      6.2       true
 6     jack      2.5      false

我该怎么做?

SELECT * FROM runners LIMIT 4,以便返回上面的每一行?

我考虑过这样使用dynamic LIMIT

SELECT * FROM runners LIMIT (4+sum(disabled::int)),但这与表中到目前为止迭代的项相比,表中的每个禁用项都算在内。还会产生此错误:

  

在LIMIT中不允许使用汇总函数

runners有100,000多行和65列。什么是更有效的方法?

设置查询:

CREATE TABLE runners(
 id SERIAL,
 runner VARCHAR, 
 km_run DECIMAL,
 disabled BOOLEAN DEFAULT false,
 PRIMARY KEY (id)
);

INSERT INTO runners (runner, km_run, disabled)
VALUES ('mary', 3.5, true);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('anna', 1.5, false);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('john', 6.5, false);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('bill', 1.5, false);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('jess', 6.2, true);
INSERT INTO runners (runner, km_run, disabled)
VALUES ('jack', 2.5, false);

1 个答案:

答案 0 :(得分:1)

对于具有id的行,首先必须获得最大的disabled = false,然后是select,至少要达到id

select * from runners
where id <= (
  select coalesce(min(r.id), 4) 
  from runners r
  where (select count(*) from runners where id <= r.id and disabled = false) = 4
)

请参见demo
结果:

> id | runner | km_run | disabled
> -: | :----- | -----: | :-------
>  1 | mary   |    3.5 | t       
>  2 | anna   |    1.5 | f       
>  3 | john   |    6.5 | f       
>  4 | bill   |    1.5 | f       
>  5 | jess   |    6.2 | t       
>  6 | jack   |    2.5 | f