2015-03-31 50 views
1

我有以下兩個表(簡化架構):更新一行加入和最大

score 
----- 
id 
score 

score_history 
------------- 
id 
score_id (foreign key with score table) 
score 

我週期性填充score_history表。我想更新分數表中的每一行,分數列基於score_history中與最大id號關聯的分數。

一個例子可以是:

score entries 
+----+-------+ 
| id | score | 
+----+-------+ 
| 1 | 0  | 
| 2 | 0  | 
+----+-------+ 

score_history entries 
+----+----------+-------+ 
| id | score_id | score | 
+----+----------+-------+ 
| 1 | 1  | 15 | 
| 2 | 2  | 10 | 
| 3 | 1  | 14 | 
| 4 | 2  | 11 | 
+----+----------+-------+ 

項3/4 score_history存在之前,我想,在一個請求,以更新從評分表分數是以下幾點:

+----+-------+ 
| id | score | 
+----+-------+ 
| 1 | 15 | 
| 2 | 10 | 
+----+-------+ 

+----+-------+ 
| id | score | 
+----+-------+ 
| 1 | 14 | 
| 2 | 11 | 
+----+-------+ 
:將條目score_history 3/4,我再次被有我的成績表像相同的請求喜歡

我嘗試了很多東西(如https://stackoverflow.com/a/9396897/916630),但無法成功。

任何想法?

回答

1

如果你正在尋找一個更新的命令,它可以像

update 
score s 
join score_history sh on sh.score_id = s.id 
join ( 
    select max(id) as max_id, score_id from score_history group by score_id 
)x on x.max_id = sh.id and x.score_id = sh.score_id 
set s.score = sh.score ; 
+0

謝謝,它工作。 – 2015-04-01 12:55:07

1
UPDATE score s 
SET score = 
    (SELECT score FROM score_history sh WHERE sh.score_id = s.ID ORDER BY SH.id ASC LIMIT 1) 
1
update score 
join score_history on score.id = score_history.score_id 
join 
(select score_id, max(id) mid 
from score_history 
group by score_id) t 
on score_history.id = t.mid 
set score.score = score_history.score 

首先獲得在歷史表中的每個score_id最大(history_id)。

然後以最大ID加入歷史記錄。

最後加入的評分表,並設置得分列具有得分最高ID

+0

此致要求似乎工作太感謝您。 – 2015-04-01 12:55:45