SQL - 更新表中的多行

时间:2015-05-28 09:26:34

标签: mysql

我正在尝试更新表中的多行,但是我无法让它一次性更新所有行。我很失落如何实现这一目标。

UPDATE ENROLMENT
INNER JOIN STUDENT ON ENROLMENT.REGNUM = STUDENT.REGNUM
INNER JOIN TOPIC ON ENROLMENT.TOPIC_NUMBER = TOPIC.TOPIC_NUMBER
SET GRADE='87' WHERE FAMILY_NAME='SMITH' and TOPIC_NAME='Internet Computing'
SET GRADE='84' WHERE FAMILY_NAME='SMITH' and TOPIC_NAME='Programming Language Concepts'
SET GRADE='60' WHERE FAMILY_NAME='BLOGGS' and TOPIC_NAME='Computer Networks'
SET GRADE='55' WHERE FAMILY_NAME='BLOGGS' and TOPIC_NAME='Internet Computing'
SET GRADE='72' WHERE FAMILY_NAME='BLOGGS' and TOPIC_NAME='Programming Language Concepts'
SET GRADE='63' WHERE FAMILY_NAME='BLACK' and TOPIC_NAME='Internet Computing';

1 个答案:

答案 0 :(得分:2)

您可以在更新集部分中使用case-when,如下所示,请注意您最后可以提供else条件,这样当没有条件匹配时,您仍然可以使用某个值进行更新。此外,最好在列名称中指定aliasname.columnname时更好的可读性,更重要的是避免歧义。

UPDATE ENROLMENT
INNER JOIN STUDENT ON ENROLMENT.REGNUM = STUDENT.REGNUM
INNER JOIN TOPIC ON ENROLMENT.TOPIC_NUMBER = TOPIC.TOPIC_NUMBER
set GRADE = 
case 
 when FAMILY_NAME='SMITH' and TOPIC_NAME='Internet Computing' then 87
 when FAMILY_NAME='SMITH' and TOPIC_NAME='Programming Language Concepts' then 84
 when FAMILY_NAME='BLOGGS' and TOPIC_NAME='Computer Networks' then 60
 when FAMILY_NAME='BLOGGS' and TOPIC_NAME='Internet Computing' then 55
 when FAMILY_NAME='BLOGGS' and TOPIC_NAME='Programming Language Concepts' then 72
 when FAMILY_NAME='BLACK' and TOPIC_NAME='Internet Computing' then 63
end;

这是使用别名

UPDATE ENROLMENT e
INNER JOIN STUDENT s ON e.REGNUM = s.REGNUM
INNER JOIN TOPIC t ON e.TOPIC_NUMBER = t.TOPIC_NUMBER
set e.GRADE = 
case 
 when s.FAMILY_NAME='SMITH' and t.TOPIC_NAME='Internet Computing' then 87
 when s.FAMILY_NAME='SMITH' and t.TOPIC_NAME='Programming Language Concepts' then 84
 when s.FAMILY_NAME='BLOGGS' and t.TOPIC_NAME='Computer Networks' then 60
 when s.FAMILY_NAME='BLOGGS' and t.TOPIC_NAME='Internet Computing' then 55
 when s.FAMILY_NAME='BLOGGS' and t.TOPIC_NAME='Programming Language Concepts' then 72
 when s.FAMILY_NAME='BLACK' and t.TOPIC_NAME='Internet Computing' then 63
end;