2017-09-15 84 views
0

是否可以使用子查詢更新多行的多個字段?使用子查詢更新多行的多個字段

cdu_user_progress:

------------------------------------------ 
|id |lesson_id |game_id |score |duration | 
------------------------------------------ 
|1 |1   |0  |50 |2500  | 
|1 |1   |1  |75 |2500  | 
|1 |2   |0  |0  |10000 | 
|1 |3   |0  |25 |1000  | 
|1 |3   |1  |25 |40000 | 
|1 |3   |2  |90 |3000  | 
|1 |4   |0  |50 |5000  | 
------------------------------------------ 

cdu_user_progress2

------------------------------------------ 
|id |lesson_id |game_id |score |duration | 
------------------------------------------ 
|1 |1   |0  |0  |0  | 
|1 |1   |1  |0  |0  | 
|1 |2   |0  |0  |0  | 
|1 |3   |0  |0  |0  | 
|1 |3   |1  |0  |0  | 
|1 |3   |2  |0  |0  | 
|1 |4   |0  |0  |0  | 
------------------------------------------ 

也許這樣的事情?

UPDATE cdu_user_progress2 
SET 
    score = sq.score, 
    duration = sq.duration 
FROM (
    SELECT 
     up.lesson_id AS lesson_id, 
     up.game_id AS game_id, 
     up.score AS score, 
     up.duration AS duration 
    FROM 
     cdu_user_progress up 
) sq 
WHERE 
    lesson_id = sq.lesson_id AND 
    game_id = sq.game_id 

我已經簡化爲這篇文章的目的,表和查詢,但原理是一樣的...

任何幫助表示讚賞!

回答

0

剛剛加入這兩個表:

UPDATE cdu_user_progress2 AS up2 
JOIN cdu_user_progress AS up ON up2.lesson_id = up.lesson_id AND up2.game_id = up.game_id 
SET up.score = up2.score, up.duration = up2.duration