MySQL——一个语句中有多个更新?

2024-10-17 10:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在MySQL中有一个表如下所示:

studentIDsubjectIDanotherIDanotherID2AnotherID3studentScore

此表中有大约100M个学生记录。


假设我将以下信息存储在两个python列表中:

listStudentIDs=[112335524425653]

listNewScores=[12.76,73.2,83.893,92.3,53.6]

如果且仅当学生在listNewScores中的分数大于其当前存储在数据库中的分数(studentScore)时,是否可以有one query更新所有studentScore字段(其ID位于listStudentIDs)的功能?


Tags: 信息id数据库列表记录mysqlqueryone
3条回答

在您的示例中,它们是5个学生ID,只有4个分数需要更新。

如果要更新的学生列表不长,则可以在一个查询中进行更新,如下所示:

UPDATE t_student
SET studentScore = CASE
 WHEN studentID=1    THEN 12.76
 WHEN studentID=123  THEN 73.2
 WHEN studentID=33   THEN 83.893
 WHEN studentID=5524 THEN 92.3
 ELSE studentScore END
WHERE studentID IN (1, 123, 33, 5524, 425653)

尽管如此,使用包含以下几个查询的SQL语句的可能性较小:

UPDATE t_student SET studentScore = 12.76  WHERE studentID = 1;
UPDATE t_student SET studentScore = 73.2   WHERE studentID = 123;
UPDATE t_student SET studentScore = 83.893 WHERE studentID = 33;
UPDATE t_student SET studentScore = 92.3   WHERE studentID = 5524;

不幸的是,MySql无法处理这个问题。否则,我会一直用它!

尝试将两个列表放入临时表(studentID,studentScore)。

然后您应该能够运行一个查询来相应地更新主表。

UPDATE studentTable t1 
JOIN tempTable t2 ON t1.studentID = t2.studentID 
SET t1.studentScore = t2.studentScore WHERE t2.studentScore > t1.studentScore

相关问题 更多 >