Last active
March 24, 2017 02:33
-
-
Save Gurpartap/e8d19272b7c996ce10239bb60a787f41 to your computer and use it in GitHub Desktop.
select x where latest y of x is z
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create table tasks ( | |
id serial primary key, | |
name text not null | |
); | |
create table results ( | |
id serial primary key, | |
created_at timestamptz default now() not null, | |
state text default null, | |
task_id int references tasks(id) | |
); | |
insert into tasks (name) values ('task_1'); | |
insert into tasks (name) values ('task_2'); | |
insert into tasks (name) values ('task_3'); | |
insert into tasks (name) values ('task_4'); | |
insert into tasks (name) values ('task_5'); | |
insert into results (state, task_id) values ('completed', 1); | |
insert into results (state, task_id) values ('failed', 2); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
begin; | |
select task.* | |
from tasks task | |
left join lateral ( | |
select _r.state | |
from task_results _r | |
where _r.task_id = task.id | |
order by _r.created_at desc | |
limit 1 | |
) result on true | |
where task.name = $1::text | |
and (result is null or result.state not in ('completed', 'failed')) | |
limit 1 | |
for update of task | |
skip locked | |
; | |
commit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment