gpt4 book ai didi

mysql - 使用条件更新 - 重复 key 更新

转载 作者:行者123 更新时间:2023-11-29 13:55:52 24 4
gpt4 key购买 nike

我有一个名为“RESULT”的表,我从另一个名为“Temp_main”的表中获取其值

“RESULT”中的字段如下所示:

StudentName | SujectName | Result
---------------------------------
Adam | Math | Fail
Bob | History | Pass
Catherine | Math | Pass
Dave | Science | Fail
Evan | History | Pass

这里的主键是(StudentName,SubjectName)

我使用以下代码将数据放入表中:

insert into result(studentName,subjectName,result)
select StudentName,SubjectName,result
from temp_main

temp_main表没有相同的主键,因此当我将数据插入结果表时,会出现重复的键值。

假设一名学生多次参加同一科目的考试。他的所有尝试都在 temp_main 表中,而只有他的最佳结果在 Result 表中。

我正在尝试获取一个ON DUPLICATE KEY UPDATE代码来更新学生-科目对的结果当且仅当最新结果为“通过”

我试过了

    insert into result(studentName,subjectName,result)
select StudentName,SubjectName,result
from temp_main
on duplicate key update result = case when temp_main(result) = 'Pass'
Then result(result)='Pass'

我确信这是蹩脚的代码。但我找不到更好的解决方案。

最佳答案

您的 SQL 中缺少 END

INSERT INTO result(studentName,subjectName,result)
SELECT StudentName,SubjectName,result
FROM temp_main
ON DUPLICATE KEY UPDATE result.result = CASE WHEN result.result = 'Pass' THEN 'Pass' ELSE VALUES(result.result) END

关于mysql - 使用条件更新 - 重复 key 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15882475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com