2012-11-25 63 views
2

我們有這些表:查詢不能如預期

player(id,salary,bonus) 

productivity_per_year(id,goals,year) 

生產力表(ID,目標,年度)

+----+-------+------+ 
| ID | Goals | Year | 
+----+-------+------+ 
| 01 | 20 | 2001 | 
| 01 | 30 | 2002 | 
| 02 | 30 | 2001 | 
| 02 | 40 | 2002 | 
+----+-------+------+ 

的問題是,我怎麼能提高獎金如果最近兩年(2001年和2002年)的球員擊球達到30個或更多目標,則爲球員。例如,在這裏,我希望獲得ID = 02的玩家的獎金,因爲他在2001年和2002年都獲得了> = 30的獎勵。

我正在使用下面的過程,但它失敗了,因爲它增加了兩個玩家的獎金!

create or replace 
procedure football 
AS 
BEGIN 
    update player p 
     set p.bonus = p.bonus + 500 
    where p.id in 
     (select s.id from productivity s where 
      s.goals >30 
     and s.year>=2001 
     and s.id = p.id 
     ); 
END; 

回答

1

兩個球員得到一個更大的獎金爲雙方球員自2001年以來得分超過30個球這是你與你的查詢做什麼。但是,只給在2001年和2002年打入超過30個球的球員提供獎金,您可以嘗試以下查詢。

update player p 
set bonus = bonus + 500 
where p.id in 
((select s.id from productivity s where s.goals > 30 and s.year = 2001 and s.id = p.id) 
intersect 
(select s.id from productivity s where s.goals > 30 and s.year = 2002 and s.id = p.id)); 

使用postgresql它的工作原理。