如何使用自联接更新?

时间:2013-12-11 03:47:33

标签: sql postgresql

我有一个postgres表,包含这样的选举结果:

CREATE TABLE results
(
  seats character varying(255),
  candidate character varying(255),
  party character varying(255),
  votes numeric(10,0)
  status character varying(2)
)

我可以使用以下查询获取获奖者的姓名:

select r.seats, r.candidate, r.votes
FROM results r
join(
select seats as s, max(votes) as mv
FROM results
group by seats) as a
on r.seats=a.s AND r.votes=a.mv;

现在我希望将所有这些获胜者的status列设置为等于'W',但我无法编写SQL查询来执行此操作。

我已经尝试过此查询,但它会将所有行的status设置为“W”:

update results set status='W'
FROM results r
join(
select seats as s, max(votes) as mv
FROM results
group by seats) as a
on r.seats=a.s AND r.votes=a.mv; 

如何编写Update..From查询以仅更新包含第一个查询获得的“获胜者”的行?

1 个答案:

答案 0 :(得分:1)

update results as r set
    status = 'W'
from (
    select t.seats, max(t.votes) as max_votes
    from results as t
    group by t.seats
) as a
where a.seats = r.seats and a.max_votes = r.votes;