mysql - 使用子查询更新多行的多个字段

标签 mysql sql

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

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

出于本文的目的,我简化了表格和查询,但原理是相同的......

感谢任何帮助!

最佳答案

只需连接两个表:

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

关于mysql - 使用子查询更新多行的多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46248178/

相关文章:

mysql - 在数据库升级后在 MySQL 中选择一个枚举不起作用,为什么?

mysql - 在同一查询中从多个组中选择一行

php - 表单提交未将数据输入数据库

mysql - 按字符串计数并按小时分组

mysql替换字符串的一部分

mysql - 如何使用逗号从数据库中选择数据

mysql - 我想获取一个月内的一些行值作为列日明智

sql - 在 dbplyr SQL 查询中的 string::str_detect 中使用带有正则表达式的变量

mysql 在列中以逗号分隔值选择行

python - (Python) MySQL 数据库身份验证问题