UPDATE userTable
SET userAge=245, userName="fred" WHERE userId = 321,
SET userAge=32, userName="dave" WHERE userId = 424;
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来编写这段代码?
是的,使用case声明:
UPDATE userTable
SET userAge= (case when userId = 321 then 245 else 32 end),
userName= (case when userId = 321 then 'fred' else 'dave' end)
WHERE userId in (321, 424);
Run Code Online (Sandbox Code Playgroud)
但是,我认为更通用的方法是使用join语法:
UPDATE userTable join
(select 321 as UserId, 'fred' as userName, 245 as userAge union all
select 424, 'dave', 32
) toupdate
on userTable.userId = toupdate.UserId
set userTable.userAge = toupdate.userAge,
userTable.userName = toupdate.userName;
Run Code Online (Sandbox Code Playgroud)
这样可以更轻松地添加更多行,并显示使用的join功能update.
编辑:
关于表现.两个更新需要在数据库中设置两个事务; 一次更新只需要一次.因此,一次更新可能会更快一点.只有在没有索引的情况下,性能差异才会明显userTable(userId).使用这样的索引,两个版本(带有where子句和使用join)都应该使用索引来查找要快速更新的行.
但是,有一个更重要的区别.两次更新使表在更新之间处于不一致状态 - 用户ID和名称在这些更新之间不一致.如果第二个失败或有人使用该表,它们将具有不一致的数据.您希望同时执行这两个更新(您也可以通过使用显式事务来解决此问题,但为什么要这么麻烦?).
UPDATE userTable
SET userAge = case when userId = 321 then 245
when userId = 424 then 32
end,
userName = case when userId = 321 then "fred"
when userId = 424 then "dave"
end
WHERE userId in (321, 424)
Run Code Online (Sandbox Code Playgroud)