cron
、pgAgent
または同様のジョブスケジューラを使用してのみ、このようなことを行うことができます。
しかし、このようにする必要はありません。次のようなテーブルを使用してください。
create table election_candidates (
election_id int not null references elections(election_id),
user_id int not null references users(user_id),
votes int not null default 0
);
create index election_candidates_election_id_votes_idx
on election_candidates(election_id, votes);
選挙が開始さelection_candidates
れると、すべての候補者の行を で作成しvotes=0
ます。投票を受け取ったら、 を使用しますupdate election_candidates set votes=votes+1 where election_id=? and user_id=?
。投票を記録する必要がある場合は、別のテーブルでそれを行い、トリガーを使用してこのテーブルを更新します。
勝者を確認する必要がある場合は、次を使用します。
with max_votes as (
select election_id, max(votes) as max_vote from election_candidates
where election_id=?
group by election_id
)
select user_id from election_candidates
natural inner join max_votes
where votes=max_vote;
ただし、複数の候補者が同数の票を獲得した場合、複数の勝者が存在する可能性があることに注意してください。